pdf.js 334 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625
  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. /* jshint globalstrict: false */
  16. /* umdutils ignore */
  17. (function (root, factory) {
  18. 'use strict';
  19. if (typeof define === 'function' && define.amd) {
  20. define('pdfjs-dist/build/pdf', ['exports'], factory);
  21. } else if (typeof exports !== 'undefined') {
  22. factory(exports);
  23. } else {
  24. factory((root.pdfjsDistBuildPdf = {}));
  25. }
  26. }(this, function (exports) {
  27. // Use strict in our context only - users might not want it
  28. 'use strict';
  29. var pdfjsVersion = '1.4.143';
  30. var pdfjsBuild = '21ed8ff';
  31. var pdfjsFilePath =
  32. typeof document !== 'undefined' && document.currentScript ?
  33. document.currentScript.src : null;
  34. var pdfjsLibs = {};
  35. (function pdfjsWrapper() {
  36. (function (root, factory) {
  37. {
  38. factory((root.pdfjsSharedGlobal = {}));
  39. }
  40. }(this, function (exports) {
  41. var globalScope = (typeof window !== 'undefined') ? window :
  42. (typeof global !== 'undefined') ? global :
  43. (typeof self !== 'undefined') ? self : this;
  44. var isWorker = (typeof window === 'undefined');
  45. // The global PDFJS object exposes the API
  46. // In production, it will be declared outside a global wrapper
  47. // In development, it will be declared here
  48. if (!globalScope.PDFJS) {
  49. globalScope.PDFJS = {};
  50. }
  51. if (typeof pdfjsVersion !== 'undefined') {
  52. globalScope.PDFJS.version = pdfjsVersion;
  53. }
  54. if (typeof pdfjsVersion !== 'undefined') {
  55. globalScope.PDFJS.build = pdfjsBuild;
  56. }
  57. globalScope.PDFJS.pdfBug = false;
  58. exports.globalScope = globalScope;
  59. exports.isWorker = isWorker;
  60. exports.PDFJS = globalScope.PDFJS;
  61. }));
  62. (function (root, factory) {
  63. {
  64. factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedGlobal);
  65. }
  66. }(this, function (exports, sharedGlobal) {
  67. var PDFJS = sharedGlobal.PDFJS;
  68. /**
  69. * Optimised CSS custom property getter/setter.
  70. * @class
  71. */
  72. var CustomStyle = (function CustomStyleClosure() {
  73. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  74. // animate-css-transforms-firefox-webkit.html
  75. // in some versions of IE9 it is critical that ms appear in this list
  76. // before Moz
  77. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  78. var _cache = Object.create(null);
  79. function CustomStyle() {}
  80. CustomStyle.getProp = function get(propName, element) {
  81. // check cache only when no element is given
  82. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  83. return _cache[propName];
  84. }
  85. element = element || document.documentElement;
  86. var style = element.style, prefixed, uPropName;
  87. // test standard property first
  88. if (typeof style[propName] === 'string') {
  89. return (_cache[propName] = propName);
  90. }
  91. // capitalize
  92. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  93. // test vendor specific properties
  94. for (var i = 0, l = prefixes.length; i < l; i++) {
  95. prefixed = prefixes[i] + uPropName;
  96. if (typeof style[prefixed] === 'string') {
  97. return (_cache[propName] = prefixed);
  98. }
  99. }
  100. //if all fails then set to undefined
  101. return (_cache[propName] = 'undefined');
  102. };
  103. CustomStyle.setProp = function set(propName, element, str) {
  104. var prop = this.getProp(propName);
  105. if (prop !== 'undefined') {
  106. element.style[prop] = str;
  107. }
  108. };
  109. return CustomStyle;
  110. })();
  111. PDFJS.CustomStyle = CustomStyle;
  112. exports.CustomStyle = CustomStyle;
  113. }));
  114. (function (root, factory) {
  115. {
  116. factory((root.pdfjsSharedUtil = {}), root.pdfjsSharedGlobal);
  117. }
  118. }(this, function (exports, sharedGlobal) {
  119. var PDFJS = sharedGlobal.PDFJS;
  120. var globalScope = sharedGlobal.globalScope;
  121. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  122. var TextRenderingMode = {
  123. FILL: 0,
  124. STROKE: 1,
  125. FILL_STROKE: 2,
  126. INVISIBLE: 3,
  127. FILL_ADD_TO_PATH: 4,
  128. STROKE_ADD_TO_PATH: 5,
  129. FILL_STROKE_ADD_TO_PATH: 6,
  130. ADD_TO_PATH: 7,
  131. FILL_STROKE_MASK: 3,
  132. ADD_TO_PATH_FLAG: 4
  133. };
  134. var ImageKind = {
  135. GRAYSCALE_1BPP: 1,
  136. RGB_24BPP: 2,
  137. RGBA_32BPP: 3
  138. };
  139. var AnnotationType = {
  140. TEXT: 1,
  141. LINK: 2,
  142. FREETEXT: 3,
  143. LINE: 4,
  144. SQUARE: 5,
  145. CIRCLE: 6,
  146. POLYGON: 7,
  147. POLYLINE: 8,
  148. HIGHLIGHT: 9,
  149. UNDERLINE: 10,
  150. SQUIGGLY: 11,
  151. STRIKEOUT: 12,
  152. STAMP: 13,
  153. CARET: 14,
  154. INK: 15,
  155. POPUP: 16,
  156. FILEATTACHMENT: 17,
  157. SOUND: 18,
  158. MOVIE: 19,
  159. WIDGET: 20,
  160. SCREEN: 21,
  161. PRINTERMARK: 22,
  162. TRAPNET: 23,
  163. WATERMARK: 24,
  164. THREED: 25,
  165. REDACT: 26
  166. };
  167. var AnnotationFlag = {
  168. INVISIBLE: 0x01,
  169. HIDDEN: 0x02,
  170. PRINT: 0x04,
  171. NOZOOM: 0x08,
  172. NOROTATE: 0x10,
  173. NOVIEW: 0x20,
  174. READONLY: 0x40,
  175. LOCKED: 0x80,
  176. TOGGLENOVIEW: 0x100,
  177. LOCKEDCONTENTS: 0x200
  178. };
  179. var AnnotationBorderStyleType = {
  180. SOLID: 1,
  181. DASHED: 2,
  182. BEVELED: 3,
  183. INSET: 4,
  184. UNDERLINE: 5
  185. };
  186. var StreamType = {
  187. UNKNOWN: 0,
  188. FLATE: 1,
  189. LZW: 2,
  190. DCT: 3,
  191. JPX: 4,
  192. JBIG: 5,
  193. A85: 6,
  194. AHX: 7,
  195. CCF: 8,
  196. RL: 9
  197. };
  198. var FontType = {
  199. UNKNOWN: 0,
  200. TYPE1: 1,
  201. TYPE1C: 2,
  202. CIDFONTTYPE0: 3,
  203. CIDFONTTYPE0C: 4,
  204. TRUETYPE: 5,
  205. CIDFONTTYPE2: 6,
  206. TYPE3: 7,
  207. OPENTYPE: 8,
  208. TYPE0: 9,
  209. MMTYPE1: 10
  210. };
  211. PDFJS.VERBOSITY_LEVELS = {
  212. errors: 0,
  213. warnings: 1,
  214. infos: 5
  215. };
  216. // All the possible operations for an operator list.
  217. var OPS = PDFJS.OPS = {
  218. // Intentionally start from 1 so it is easy to spot bad operators that will be
  219. // 0's.
  220. dependency: 1,
  221. setLineWidth: 2,
  222. setLineCap: 3,
  223. setLineJoin: 4,
  224. setMiterLimit: 5,
  225. setDash: 6,
  226. setRenderingIntent: 7,
  227. setFlatness: 8,
  228. setGState: 9,
  229. save: 10,
  230. restore: 11,
  231. transform: 12,
  232. moveTo: 13,
  233. lineTo: 14,
  234. curveTo: 15,
  235. curveTo2: 16,
  236. curveTo3: 17,
  237. closePath: 18,
  238. rectangle: 19,
  239. stroke: 20,
  240. closeStroke: 21,
  241. fill: 22,
  242. eoFill: 23,
  243. fillStroke: 24,
  244. eoFillStroke: 25,
  245. closeFillStroke: 26,
  246. closeEOFillStroke: 27,
  247. endPath: 28,
  248. clip: 29,
  249. eoClip: 30,
  250. beginText: 31,
  251. endText: 32,
  252. setCharSpacing: 33,
  253. setWordSpacing: 34,
  254. setHScale: 35,
  255. setLeading: 36,
  256. setFont: 37,
  257. setTextRenderingMode: 38,
  258. setTextRise: 39,
  259. moveText: 40,
  260. setLeadingMoveText: 41,
  261. setTextMatrix: 42,
  262. nextLine: 43,
  263. showText: 44,
  264. showSpacedText: 45,
  265. nextLineShowText: 46,
  266. nextLineSetSpacingShowText: 47,
  267. setCharWidth: 48,
  268. setCharWidthAndBounds: 49,
  269. setStrokeColorSpace: 50,
  270. setFillColorSpace: 51,
  271. setStrokeColor: 52,
  272. setStrokeColorN: 53,
  273. setFillColor: 54,
  274. setFillColorN: 55,
  275. setStrokeGray: 56,
  276. setFillGray: 57,
  277. setStrokeRGBColor: 58,
  278. setFillRGBColor: 59,
  279. setStrokeCMYKColor: 60,
  280. setFillCMYKColor: 61,
  281. shadingFill: 62,
  282. beginInlineImage: 63,
  283. beginImageData: 64,
  284. endInlineImage: 65,
  285. paintXObject: 66,
  286. markPoint: 67,
  287. markPointProps: 68,
  288. beginMarkedContent: 69,
  289. beginMarkedContentProps: 70,
  290. endMarkedContent: 71,
  291. beginCompat: 72,
  292. endCompat: 73,
  293. paintFormXObjectBegin: 74,
  294. paintFormXObjectEnd: 75,
  295. beginGroup: 76,
  296. endGroup: 77,
  297. beginAnnotations: 78,
  298. endAnnotations: 79,
  299. beginAnnotation: 80,
  300. endAnnotation: 81,
  301. paintJpegXObject: 82,
  302. paintImageMaskXObject: 83,
  303. paintImageMaskXObjectGroup: 84,
  304. paintImageXObject: 85,
  305. paintInlineImageXObject: 86,
  306. paintInlineImageXObjectGroup: 87,
  307. paintImageXObjectRepeat: 88,
  308. paintImageMaskXObjectRepeat: 89,
  309. paintSolidColorImageMask: 90,
  310. constructPath: 91
  311. };
  312. // A notice for devs. These are good for things that are helpful to devs, such
  313. // as warning that Workers were disabled, which is important to devs but not
  314. // end users.
  315. function info(msg) {
  316. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  317. console.log('Info: ' + msg);
  318. }
  319. }
  320. // Non-fatal warnings.
  321. function warn(msg) {
  322. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  323. console.log('Warning: ' + msg);
  324. }
  325. }
  326. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  327. function deprecated(details) {
  328. console.log('Deprecated API usage: ' + details);
  329. }
  330. // Fatal errors that should trigger the fallback UI and halt execution by
  331. // throwing an exception.
  332. function error(msg) {
  333. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
  334. console.log('Error: ' + msg);
  335. console.log(backtrace());
  336. }
  337. throw new Error(msg);
  338. }
  339. function backtrace() {
  340. try {
  341. throw new Error();
  342. } catch (e) {
  343. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  344. }
  345. }
  346. function assert(cond, msg) {
  347. if (!cond) {
  348. error(msg);
  349. }
  350. }
  351. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  352. unknown: 'unknown',
  353. forms: 'forms',
  354. javaScript: 'javaScript',
  355. smask: 'smask',
  356. shadingPattern: 'shadingPattern',
  357. font: 'font'
  358. };
  359. // Gets the file name from a given URL.
  360. function getFilenameFromUrl(url) {
  361. var anchor = url.indexOf('#');
  362. var query = url.indexOf('?');
  363. var end = Math.min(
  364. anchor > 0 ? anchor : url.length,
  365. query > 0 ? query : url.length);
  366. return url.substring(url.lastIndexOf('/', end) + 1, end);
  367. }
  368. PDFJS.getFilenameFromUrl = getFilenameFromUrl;
  369. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  370. // absolute URL, it will be returned as is.
  371. function combineUrl(baseUrl, url) {
  372. if (!url) {
  373. return baseUrl;
  374. }
  375. return new URL(url, baseUrl).href;
  376. }
  377. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  378. function isSameOrigin(baseUrl, otherUrl) {
  379. try {
  380. var base = new URL(baseUrl);
  381. if (!base.origin || base.origin === 'null') {
  382. return false; // non-HTTP url
  383. }
  384. } catch (e) {
  385. return false;
  386. }
  387. var other = new URL(otherUrl, base);
  388. return base.origin === other.origin;
  389. }
  390. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  391. function isValidUrl(url, allowRelative) {
  392. if (!url) {
  393. return false;
  394. }
  395. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  396. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  397. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  398. if (!protocol) {
  399. return allowRelative;
  400. }
  401. protocol = protocol[0].toLowerCase();
  402. switch (protocol) {
  403. case 'http':
  404. case 'https':
  405. case 'ftp':
  406. case 'mailto':
  407. case 'tel':
  408. return true;
  409. default:
  410. return false;
  411. }
  412. }
  413. PDFJS.isValidUrl = isValidUrl;
  414. /**
  415. * Adds various attributes (href, title, target, rel) to hyperlinks.
  416. * @param {HTMLLinkElement} link - The link element.
  417. * @param {Object} params - An object with the properties:
  418. * @param {string} params.url - An absolute URL.
  419. */
  420. function addLinkAttributes(link, params) {
  421. var url = params && params.url;
  422. link.href = link.title = (url ? removeNullCharacters(url) : '');
  423. if (url) {
  424. if (isExternalLinkTargetSet()) {
  425. link.target = LinkTargetStringMap[PDFJS.externalLinkTarget];
  426. }
  427. // Strip referrer from the URL.
  428. link.rel = PDFJS.externalLinkRel;
  429. }
  430. }
  431. PDFJS.addLinkAttributes = addLinkAttributes;
  432. function shadow(obj, prop, value) {
  433. Object.defineProperty(obj, prop, { value: value,
  434. enumerable: true,
  435. configurable: true,
  436. writable: false });
  437. return value;
  438. }
  439. PDFJS.shadow = shadow;
  440. function getLookupTableFactory(initializer) {
  441. var lookup;
  442. return function () {
  443. if (initializer) {
  444. lookup = Object.create(null);
  445. initializer(lookup);
  446. initializer = null;
  447. }
  448. return lookup;
  449. };
  450. }
  451. var LinkTarget = PDFJS.LinkTarget = {
  452. NONE: 0, // Default value.
  453. SELF: 1,
  454. BLANK: 2,
  455. PARENT: 3,
  456. TOP: 4,
  457. };
  458. var LinkTargetStringMap = [
  459. '',
  460. '_self',
  461. '_blank',
  462. '_parent',
  463. '_top'
  464. ];
  465. function isExternalLinkTargetSet() {
  466. if (PDFJS.openExternalLinksInNewWindow) {
  467. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  468. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  469. if (PDFJS.externalLinkTarget === LinkTarget.NONE) {
  470. PDFJS.externalLinkTarget = LinkTarget.BLANK;
  471. }
  472. // Reset the deprecated parameter, to suppress further warnings.
  473. PDFJS.openExternalLinksInNewWindow = false;
  474. }
  475. switch (PDFJS.externalLinkTarget) {
  476. case LinkTarget.NONE:
  477. return false;
  478. case LinkTarget.SELF:
  479. case LinkTarget.BLANK:
  480. case LinkTarget.PARENT:
  481. case LinkTarget.TOP:
  482. return true;
  483. }
  484. warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget);
  485. // Reset the external link target, to suppress further warnings.
  486. PDFJS.externalLinkTarget = LinkTarget.NONE;
  487. return false;
  488. }
  489. PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet;
  490. var PasswordResponses = PDFJS.PasswordResponses = {
  491. NEED_PASSWORD: 1,
  492. INCORRECT_PASSWORD: 2
  493. };
  494. var PasswordException = (function PasswordExceptionClosure() {
  495. function PasswordException(msg, code) {
  496. this.name = 'PasswordException';
  497. this.message = msg;
  498. this.code = code;
  499. }
  500. PasswordException.prototype = new Error();
  501. PasswordException.constructor = PasswordException;
  502. return PasswordException;
  503. })();
  504. PDFJS.PasswordException = PasswordException;
  505. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  506. function UnknownErrorException(msg, details) {
  507. this.name = 'UnknownErrorException';
  508. this.message = msg;
  509. this.details = details;
  510. }
  511. UnknownErrorException.prototype = new Error();
  512. UnknownErrorException.constructor = UnknownErrorException;
  513. return UnknownErrorException;
  514. })();
  515. PDFJS.UnknownErrorException = UnknownErrorException;
  516. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  517. function InvalidPDFException(msg) {
  518. this.name = 'InvalidPDFException';
  519. this.message = msg;
  520. }
  521. InvalidPDFException.prototype = new Error();
  522. InvalidPDFException.constructor = InvalidPDFException;
  523. return InvalidPDFException;
  524. })();
  525. PDFJS.InvalidPDFException = InvalidPDFException;
  526. var MissingPDFException = (function MissingPDFExceptionClosure() {
  527. function MissingPDFException(msg) {
  528. this.name = 'MissingPDFException';
  529. this.message = msg;
  530. }
  531. MissingPDFException.prototype = new Error();
  532. MissingPDFException.constructor = MissingPDFException;
  533. return MissingPDFException;
  534. })();
  535. PDFJS.MissingPDFException = MissingPDFException;
  536. var UnexpectedResponseException =
  537. (function UnexpectedResponseExceptionClosure() {
  538. function UnexpectedResponseException(msg, status) {
  539. this.name = 'UnexpectedResponseException';
  540. this.message = msg;
  541. this.status = status;
  542. }
  543. UnexpectedResponseException.prototype = new Error();
  544. UnexpectedResponseException.constructor = UnexpectedResponseException;
  545. return UnexpectedResponseException;
  546. })();
  547. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  548. var NotImplementedException = (function NotImplementedExceptionClosure() {
  549. function NotImplementedException(msg) {
  550. this.message = msg;
  551. }
  552. NotImplementedException.prototype = new Error();
  553. NotImplementedException.prototype.name = 'NotImplementedException';
  554. NotImplementedException.constructor = NotImplementedException;
  555. return NotImplementedException;
  556. })();
  557. var MissingDataException = (function MissingDataExceptionClosure() {
  558. function MissingDataException(begin, end) {
  559. this.begin = begin;
  560. this.end = end;
  561. this.message = 'Missing data [' + begin + ', ' + end + ')';
  562. }
  563. MissingDataException.prototype = new Error();
  564. MissingDataException.prototype.name = 'MissingDataException';
  565. MissingDataException.constructor = MissingDataException;
  566. return MissingDataException;
  567. })();
  568. var XRefParseException = (function XRefParseExceptionClosure() {
  569. function XRefParseException(msg) {
  570. this.message = msg;
  571. }
  572. XRefParseException.prototype = new Error();
  573. XRefParseException.prototype.name = 'XRefParseException';
  574. XRefParseException.constructor = XRefParseException;
  575. return XRefParseException;
  576. })();
  577. var NullCharactersRegExp = /\x00/g;
  578. function removeNullCharacters(str) {
  579. if (typeof str !== 'string') {
  580. warn('The argument for removeNullCharacters must be a string.');
  581. return str;
  582. }
  583. return str.replace(NullCharactersRegExp, '');
  584. }
  585. PDFJS.removeNullCharacters = removeNullCharacters;
  586. function bytesToString(bytes) {
  587. assert(bytes !== null && typeof bytes === 'object' &&
  588. bytes.length !== undefined, 'Invalid argument for bytesToString');
  589. var length = bytes.length;
  590. var MAX_ARGUMENT_COUNT = 8192;
  591. if (length < MAX_ARGUMENT_COUNT) {
  592. return String.fromCharCode.apply(null, bytes);
  593. }
  594. var strBuf = [];
  595. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  596. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  597. var chunk = bytes.subarray(i, chunkEnd);
  598. strBuf.push(String.fromCharCode.apply(null, chunk));
  599. }
  600. return strBuf.join('');
  601. }
  602. function stringToBytes(str) {
  603. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  604. var length = str.length;
  605. var bytes = new Uint8Array(length);
  606. for (var i = 0; i < length; ++i) {
  607. bytes[i] = str.charCodeAt(i) & 0xFF;
  608. }
  609. return bytes;
  610. }
  611. /**
  612. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  613. * @param {Array|Uint8Array|string} arr
  614. * @returns {number}
  615. */
  616. function arrayByteLength(arr) {
  617. if (arr.length !== undefined) {
  618. return arr.length;
  619. }
  620. assert(arr.byteLength !== undefined);
  621. return arr.byteLength;
  622. }
  623. /**
  624. * Combines array items (arrays) into single Uint8Array object.
  625. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  626. * @returns {Uint8Array}
  627. */
  628. function arraysToBytes(arr) {
  629. // Shortcut: if first and only item is Uint8Array, return it.
  630. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) {
  631. return arr[0];
  632. }
  633. var resultLength = 0;
  634. var i, ii = arr.length;
  635. var item, itemLength ;
  636. for (i = 0; i < ii; i++) {
  637. item = arr[i];
  638. itemLength = arrayByteLength(item);
  639. resultLength += itemLength;
  640. }
  641. var pos = 0;
  642. var data = new Uint8Array(resultLength);
  643. for (i = 0; i < ii; i++) {
  644. item = arr[i];
  645. if (!(item instanceof Uint8Array)) {
  646. if (typeof item === 'string') {
  647. item = stringToBytes(item);
  648. } else {
  649. item = new Uint8Array(item);
  650. }
  651. }
  652. itemLength = item.byteLength;
  653. data.set(item, pos);
  654. pos += itemLength;
  655. }
  656. return data;
  657. }
  658. function string32(value) {
  659. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  660. (value >> 8) & 0xff, value & 0xff);
  661. }
  662. function log2(x) {
  663. var n = 1, i = 0;
  664. while (x > n) {
  665. n <<= 1;
  666. i++;
  667. }
  668. return i;
  669. }
  670. function readInt8(data, start) {
  671. return (data[start] << 24) >> 24;
  672. }
  673. function readUint16(data, offset) {
  674. return (data[offset] << 8) | data[offset + 1];
  675. }
  676. function readUint32(data, offset) {
  677. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  678. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  679. }
  680. // Lazy test the endianness of the platform
  681. // NOTE: This will be 'true' for simulated TypedArrays
  682. function isLittleEndian() {
  683. var buffer8 = new Uint8Array(2);
  684. buffer8[0] = 1;
  685. var buffer16 = new Uint16Array(buffer8.buffer);
  686. return (buffer16[0] === 1);
  687. }
  688. Object.defineProperty(PDFJS, 'isLittleEndian', {
  689. configurable: true,
  690. get: function PDFJS_isLittleEndian() {
  691. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  692. }
  693. });
  694. // Lazy test if the userAgent support CanvasTypedArrays
  695. function hasCanvasTypedArrays() {
  696. var canvas = document.createElement('canvas');
  697. canvas.width = canvas.height = 1;
  698. var ctx = canvas.getContext('2d');
  699. var imageData = ctx.createImageData(1, 1);
  700. return (typeof imageData.data.buffer !== 'undefined');
  701. }
  702. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  703. configurable: true,
  704. get: function PDFJS_hasCanvasTypedArrays() {
  705. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  706. }
  707. });
  708. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  709. function Uint32ArrayView(buffer, length) {
  710. this.buffer = buffer;
  711. this.byteLength = buffer.length;
  712. this.length = length === undefined ? (this.byteLength >> 2) : length;
  713. ensureUint32ArrayViewProps(this.length);
  714. }
  715. Uint32ArrayView.prototype = Object.create(null);
  716. var uint32ArrayViewSetters = 0;
  717. function createUint32ArrayProp(index) {
  718. return {
  719. get: function () {
  720. var buffer = this.buffer, offset = index << 2;
  721. return (buffer[offset] | (buffer[offset + 1] << 8) |
  722. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  723. },
  724. set: function (value) {
  725. var buffer = this.buffer, offset = index << 2;
  726. buffer[offset] = value & 255;
  727. buffer[offset + 1] = (value >> 8) & 255;
  728. buffer[offset + 2] = (value >> 16) & 255;
  729. buffer[offset + 3] = (value >>> 24) & 255;
  730. }
  731. };
  732. }
  733. function ensureUint32ArrayViewProps(length) {
  734. while (uint32ArrayViewSetters < length) {
  735. Object.defineProperty(Uint32ArrayView.prototype,
  736. uint32ArrayViewSetters,
  737. createUint32ArrayProp(uint32ArrayViewSetters));
  738. uint32ArrayViewSetters++;
  739. }
  740. }
  741. return Uint32ArrayView;
  742. })();
  743. exports.Uint32ArrayView = Uint32ArrayView;
  744. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  745. var Util = PDFJS.Util = (function UtilClosure() {
  746. function Util() {}
  747. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  748. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  749. // creating many intermediate strings.
  750. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  751. rgbBuf[1] = r;
  752. rgbBuf[3] = g;
  753. rgbBuf[5] = b;
  754. return rgbBuf.join('');
  755. };
  756. // Concatenates two transformation matrices together and returns the result.
  757. Util.transform = function Util_transform(m1, m2) {
  758. return [
  759. m1[0] * m2[0] + m1[2] * m2[1],
  760. m1[1] * m2[0] + m1[3] * m2[1],
  761. m1[0] * m2[2] + m1[2] * m2[3],
  762. m1[1] * m2[2] + m1[3] * m2[3],
  763. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  764. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  765. ];
  766. };
  767. // For 2d affine transforms
  768. Util.applyTransform = function Util_applyTransform(p, m) {
  769. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  770. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  771. return [xt, yt];
  772. };
  773. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  774. var d = m[0] * m[3] - m[1] * m[2];
  775. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  776. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  777. return [xt, yt];
  778. };
  779. // Applies the transform to the rectangle and finds the minimum axially
  780. // aligned bounding box.
  781. Util.getAxialAlignedBoundingBox =
  782. function Util_getAxialAlignedBoundingBox(r, m) {
  783. var p1 = Util.applyTransform(r, m);
  784. var p2 = Util.applyTransform(r.slice(2, 4), m);
  785. var p3 = Util.applyTransform([r[0], r[3]], m);
  786. var p4 = Util.applyTransform([r[2], r[1]], m);
  787. return [
  788. Math.min(p1[0], p2[0], p3[0], p4[0]),
  789. Math.min(p1[1], p2[1], p3[1], p4[1]),
  790. Math.max(p1[0], p2[0], p3[0], p4[0]),
  791. Math.max(p1[1], p2[1], p3[1], p4[1])
  792. ];
  793. };
  794. Util.inverseTransform = function Util_inverseTransform(m) {
  795. var d = m[0] * m[3] - m[1] * m[2];
  796. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  797. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  798. };
  799. // Apply a generic 3d matrix M on a 3-vector v:
  800. // | a b c | | X |
  801. // | d e f | x | Y |
  802. // | g h i | | Z |
  803. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  804. // with v as [X,Y,Z]
  805. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  806. return [
  807. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  808. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  809. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  810. ];
  811. };
  812. // This calculation uses Singular Value Decomposition.
  813. // The SVD can be represented with formula A = USV. We are interested in the
  814. // matrix S here because it represents the scale values.
  815. Util.singularValueDecompose2dScale =
  816. function Util_singularValueDecompose2dScale(m) {
  817. var transpose = [m[0], m[2], m[1], m[3]];
  818. // Multiply matrix m with its transpose.
  819. var a = m[0] * transpose[0] + m[1] * transpose[2];
  820. var b = m[0] * transpose[1] + m[1] * transpose[3];
  821. var c = m[2] * transpose[0] + m[3] * transpose[2];
  822. var d = m[2] * transpose[1] + m[3] * transpose[3];
  823. // Solve the second degree polynomial to get roots.
  824. var first = (a + d) / 2;
  825. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  826. var sx = first + second || 1;
  827. var sy = first - second || 1;
  828. // Scale values are the square roots of the eigenvalues.
  829. return [Math.sqrt(sx), Math.sqrt(sy)];
  830. };
  831. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  832. // For coordinate systems whose origin lies in the bottom-left, this
  833. // means normalization to (BL,TR) ordering. For systems with origin in the
  834. // top-left, this means (TL,BR) ordering.
  835. Util.normalizeRect = function Util_normalizeRect(rect) {
  836. var r = rect.slice(0); // clone rect
  837. if (rect[0] > rect[2]) {
  838. r[0] = rect[2];
  839. r[2] = rect[0];
  840. }
  841. if (rect[1] > rect[3]) {
  842. r[1] = rect[3];
  843. r[3] = rect[1];
  844. }
  845. return r;
  846. };
  847. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  848. // intersection of rect1 and rect2. If no intersection, returns 'false'
  849. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  850. Util.intersect = function Util_intersect(rect1, rect2) {
  851. function compare(a, b) {
  852. return a - b;
  853. }
  854. // Order points along the axes
  855. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  856. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  857. result = [];
  858. rect1 = Util.normalizeRect(rect1);
  859. rect2 = Util.normalizeRect(rect2);
  860. // X: first and second points belong to different rectangles?
  861. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  862. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  863. // Intersection must be between second and third points
  864. result[0] = orderedX[1];
  865. result[2] = orderedX[2];
  866. } else {
  867. return false;
  868. }
  869. // Y: first and second points belong to different rectangles?
  870. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  871. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  872. // Intersection must be between second and third points
  873. result[1] = orderedY[1];
  874. result[3] = orderedY[2];
  875. } else {
  876. return false;
  877. }
  878. return result;
  879. };
  880. Util.sign = function Util_sign(num) {
  881. return num < 0 ? -1 : 1;
  882. };
  883. var ROMAN_NUMBER_MAP = [
  884. '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  885. '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  886. '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
  887. ];
  888. /**
  889. * Converts positive integers to (upper case) Roman numerals.
  890. * @param {integer} number - The number that should be converted.
  891. * @param {boolean} lowerCase - Indicates if the result should be converted
  892. * to lower case letters. The default is false.
  893. * @return {string} The resulting Roman number.
  894. */
  895. Util.toRoman = function Util_toRoman(number, lowerCase) {
  896. assert(isInt(number) && number > 0,
  897. 'The number should be a positive integer.');
  898. var pos, romanBuf = [];
  899. // Thousands
  900. while (number >= 1000) {
  901. number -= 1000;
  902. romanBuf.push('M');
  903. }
  904. // Hundreds
  905. pos = (number / 100) | 0;
  906. number %= 100;
  907. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  908. // Tens
  909. pos = (number / 10) | 0;
  910. number %= 10;
  911. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  912. // Ones
  913. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  914. var romanStr = romanBuf.join('');
  915. return (lowerCase ? romanStr.toLowerCase() : romanStr);
  916. };
  917. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  918. Array.prototype.push.apply(arr1, arr2);
  919. };
  920. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  921. Array.prototype.unshift.apply(arr1, arr2);
  922. };
  923. Util.extendObj = function extendObj(obj1, obj2) {
  924. for (var key in obj2) {
  925. obj1[key] = obj2[key];
  926. }
  927. };
  928. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  929. name) {
  930. while (dict && !dict.has(name)) {
  931. dict = dict.get('Parent');
  932. }
  933. if (!dict) {
  934. return null;
  935. }
  936. return dict.get(name);
  937. };
  938. Util.inherit = function Util_inherit(sub, base, prototype) {
  939. sub.prototype = Object.create(base.prototype);
  940. sub.prototype.constructor = sub;
  941. for (var prop in prototype) {
  942. sub.prototype[prop] = prototype[prop];
  943. }
  944. };
  945. Util.loadScript = function Util_loadScript(src, callback) {
  946. var script = document.createElement('script');
  947. var loaded = false;
  948. script.setAttribute('src', src);
  949. if (callback) {
  950. script.onload = function() {
  951. if (!loaded) {
  952. callback();
  953. }
  954. loaded = true;
  955. };
  956. }
  957. document.getElementsByTagName('head')[0].appendChild(script);
  958. };
  959. return Util;
  960. })();
  961. /**
  962. * PDF page viewport created based on scale, rotation and offset.
  963. * @class
  964. * @alias PDFJS.PageViewport
  965. */
  966. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  967. /**
  968. * @constructor
  969. * @private
  970. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  971. * @param scale {number} scale of the viewport.
  972. * @param rotation {number} rotations of the viewport in degrees.
  973. * @param offsetX {number} offset X
  974. * @param offsetY {number} offset Y
  975. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  976. */
  977. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  978. this.viewBox = viewBox;
  979. this.scale = scale;
  980. this.rotation = rotation;
  981. this.offsetX = offsetX;
  982. this.offsetY = offsetY;
  983. // creating transform to convert pdf coordinate system to the normal
  984. // canvas like coordinates taking in account scale and rotation
  985. var centerX = (viewBox[2] + viewBox[0]) / 2;
  986. var centerY = (viewBox[3] + viewBox[1]) / 2;
  987. var rotateA, rotateB, rotateC, rotateD;
  988. rotation = rotation % 360;
  989. rotation = rotation < 0 ? rotation + 360 : rotation;
  990. switch (rotation) {
  991. case 180:
  992. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  993. break;
  994. case 90:
  995. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  996. break;
  997. case 270:
  998. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  999. break;
  1000. //case 0:
  1001. default:
  1002. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  1003. break;
  1004. }
  1005. if (dontFlip) {
  1006. rotateC = -rotateC; rotateD = -rotateD;
  1007. }
  1008. var offsetCanvasX, offsetCanvasY;
  1009. var width, height;
  1010. if (rotateA === 0) {
  1011. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  1012. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  1013. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  1014. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  1015. } else {
  1016. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  1017. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  1018. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  1019. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  1020. }
  1021. // creating transform for the following operations:
  1022. // translate(-centerX, -centerY), rotate and flip vertically,
  1023. // scale, and translate(offsetCanvasX, offsetCanvasY)
  1024. this.transform = [
  1025. rotateA * scale,
  1026. rotateB * scale,
  1027. rotateC * scale,
  1028. rotateD * scale,
  1029. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  1030. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  1031. ];
  1032. this.width = width;
  1033. this.height = height;
  1034. this.fontScale = scale;
  1035. }
  1036. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  1037. /**
  1038. * Clones viewport with additional properties.
  1039. * @param args {Object} (optional) If specified, may contain the 'scale' or
  1040. * 'rotation' properties to override the corresponding properties in
  1041. * the cloned viewport.
  1042. * @returns {PDFJS.PageViewport} Cloned viewport.
  1043. */
  1044. clone: function PageViewPort_clone(args) {
  1045. args = args || {};
  1046. var scale = 'scale' in args ? args.scale : this.scale;
  1047. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  1048. return new PageViewport(this.viewBox.slice(), scale, rotation,
  1049. this.offsetX, this.offsetY, args.dontFlip);
  1050. },
  1051. /**
  1052. * Converts PDF point to the viewport coordinates. For examples, useful for
  1053. * converting PDF location into canvas pixel coordinates.
  1054. * @param x {number} X coordinate.
  1055. * @param y {number} Y coordinate.
  1056. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1057. * point in the viewport coordinate space.
  1058. * @see {@link convertToPdfPoint}
  1059. * @see {@link convertToViewportRectangle}
  1060. */
  1061. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  1062. return Util.applyTransform([x, y], this.transform);
  1063. },
  1064. /**
  1065. * Converts PDF rectangle to the viewport coordinates.
  1066. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  1067. * @returns {Array} Contains corresponding coordinates of the rectangle
  1068. * in the viewport coordinate space.
  1069. * @see {@link convertToViewportPoint}
  1070. */
  1071. convertToViewportRectangle:
  1072. function PageViewport_convertToViewportRectangle(rect) {
  1073. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  1074. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  1075. return [tl[0], tl[1], br[0], br[1]];
  1076. },
  1077. /**
  1078. * Converts viewport coordinates to the PDF location. For examples, useful
  1079. * for converting canvas pixel location into PDF one.
  1080. * @param x {number} X coordinate.
  1081. * @param y {number} Y coordinate.
  1082. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1083. * point in the PDF coordinate space.
  1084. * @see {@link convertToViewportPoint}
  1085. */
  1086. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  1087. return Util.applyInverseTransform([x, y], this.transform);
  1088. }
  1089. };
  1090. return PageViewport;
  1091. })();
  1092. var PDFStringTranslateTable = [
  1093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1094. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  1095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  1099. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  1100. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  1101. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  1102. ];
  1103. function stringToPDFString(str) {
  1104. var i, n = str.length, strBuf = [];
  1105. if (str[0] === '\xFE' && str[1] === '\xFF') {
  1106. // UTF16BE BOM
  1107. for (i = 2; i < n; i += 2) {
  1108. strBuf.push(String.fromCharCode(
  1109. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  1110. }
  1111. } else {
  1112. for (i = 0; i < n; ++i) {
  1113. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  1114. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1115. }
  1116. }
  1117. return strBuf.join('');
  1118. }
  1119. function stringToUTF8String(str) {
  1120. return decodeURIComponent(escape(str));
  1121. }
  1122. function utf8StringToString(str) {
  1123. return unescape(encodeURIComponent(str));
  1124. }
  1125. function isEmptyObj(obj) {
  1126. for (var key in obj) {
  1127. return false;
  1128. }
  1129. return true;
  1130. }
  1131. function isBool(v) {
  1132. return typeof v === 'boolean';
  1133. }
  1134. function isInt(v) {
  1135. return typeof v === 'number' && ((v | 0) === v);
  1136. }
  1137. function isNum(v) {
  1138. return typeof v === 'number';
  1139. }
  1140. function isString(v) {
  1141. return typeof v === 'string';
  1142. }
  1143. function isArray(v) {
  1144. return v instanceof Array;
  1145. }
  1146. function isArrayBuffer(v) {
  1147. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1148. }
  1149. /**
  1150. * Promise Capability object.
  1151. *
  1152. * @typedef {Object} PromiseCapability
  1153. * @property {Promise} promise - A promise object.
  1154. * @property {function} resolve - Fullfills the promise.
  1155. * @property {function} reject - Rejects the promise.
  1156. */
  1157. /**
  1158. * Creates a promise capability object.
  1159. * @alias PDFJS.createPromiseCapability
  1160. *
  1161. * @return {PromiseCapability} A capability object contains:
  1162. * - a Promise, resolve and reject methods.
  1163. */
  1164. function createPromiseCapability() {
  1165. var capability = {};
  1166. capability.promise = new Promise(function (resolve, reject) {
  1167. capability.resolve = resolve;
  1168. capability.reject = reject;
  1169. });
  1170. return capability;
  1171. }
  1172. PDFJS.createPromiseCapability = createPromiseCapability;
  1173. /**
  1174. * Polyfill for Promises:
  1175. * The following promise implementation tries to generally implement the
  1176. * Promise/A+ spec. Some notable differences from other promise libaries are:
  1177. * - There currently isn't a seperate deferred and promise object.
  1178. * - Unhandled rejections eventually show an error if they aren't handled.
  1179. *
  1180. * Based off of the work in:
  1181. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1182. */
  1183. (function PromiseClosure() {
  1184. if (globalScope.Promise) {
  1185. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1186. if (typeof globalScope.Promise.all !== 'function') {
  1187. globalScope.Promise.all = function (iterable) {
  1188. var count = 0, results = [], resolve, reject;
  1189. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1190. resolve = resolve_;
  1191. reject = reject_;
  1192. });
  1193. iterable.forEach(function (p, i) {
  1194. count++;
  1195. p.then(function (result) {
  1196. results[i] = result;
  1197. count--;
  1198. if (count === 0) {
  1199. resolve(results);
  1200. }
  1201. }, reject);
  1202. });
  1203. if (count === 0) {
  1204. resolve(results);
  1205. }
  1206. return promise;
  1207. };
  1208. }
  1209. if (typeof globalScope.Promise.resolve !== 'function') {
  1210. globalScope.Promise.resolve = function (value) {
  1211. return new globalScope.Promise(function (resolve) { resolve(value); });
  1212. };
  1213. }
  1214. if (typeof globalScope.Promise.reject !== 'function') {
  1215. globalScope.Promise.reject = function (reason) {
  1216. return new globalScope.Promise(function (resolve, reject) {
  1217. reject(reason);
  1218. });
  1219. };
  1220. }
  1221. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1222. globalScope.Promise.prototype.catch = function (onReject) {
  1223. return globalScope.Promise.prototype.then(undefined, onReject);
  1224. };
  1225. }
  1226. return;
  1227. }
  1228. var STATUS_PENDING = 0;
  1229. var STATUS_RESOLVED = 1;
  1230. var STATUS_REJECTED = 2;
  1231. // In an attempt to avoid silent exceptions, unhandled rejections are
  1232. // tracked and if they aren't handled in a certain amount of time an
  1233. // error is logged.
  1234. var REJECTION_TIMEOUT = 500;
  1235. var HandlerManager = {
  1236. handlers: [],
  1237. running: false,
  1238. unhandledRejections: [],
  1239. pendingRejectionCheck: false,
  1240. scheduleHandlers: function scheduleHandlers(promise) {
  1241. if (promise._status === STATUS_PENDING) {
  1242. return;
  1243. }
  1244. this.handlers = this.handlers.concat(promise._handlers);
  1245. promise._handlers = [];
  1246. if (this.running) {
  1247. return;
  1248. }
  1249. this.running = true;
  1250. setTimeout(this.runHandlers.bind(this), 0);
  1251. },
  1252. runHandlers: function runHandlers() {
  1253. var RUN_TIMEOUT = 1; // ms
  1254. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1255. while (this.handlers.length > 0) {
  1256. var handler = this.handlers.shift();
  1257. var nextStatus = handler.thisPromise._status;
  1258. var nextValue = handler.thisPromise._value;
  1259. try {
  1260. if (nextStatus === STATUS_RESOLVED) {
  1261. if (typeof handler.onResolve === 'function') {
  1262. nextValue = handler.onResolve(nextValue);
  1263. }
  1264. } else if (typeof handler.onReject === 'function') {
  1265. nextValue = handler.onReject(nextValue);
  1266. nextStatus = STATUS_RESOLVED;
  1267. if (handler.thisPromise._unhandledRejection) {
  1268. this.removeUnhandeledRejection(handler.thisPromise);
  1269. }
  1270. }
  1271. } catch (ex) {
  1272. nextStatus = STATUS_REJECTED;
  1273. nextValue = ex;
  1274. }
  1275. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1276. if (Date.now() >= timeoutAt) {
  1277. break;
  1278. }
  1279. }
  1280. if (this.handlers.length > 0) {
  1281. setTimeout(this.runHandlers.bind(this), 0);
  1282. return;
  1283. }
  1284. this.running = false;
  1285. },
  1286. addUnhandledRejection: function addUnhandledRejection(promise) {
  1287. this.unhandledRejections.push({
  1288. promise: promise,
  1289. time: Date.now()
  1290. });
  1291. this.scheduleRejectionCheck();
  1292. },
  1293. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1294. promise._unhandledRejection = false;
  1295. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1296. if (this.unhandledRejections[i].promise === promise) {
  1297. this.unhandledRejections.splice(i);
  1298. i--;
  1299. }
  1300. }
  1301. },
  1302. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1303. if (this.pendingRejectionCheck) {
  1304. return;
  1305. }
  1306. this.pendingRejectionCheck = true;
  1307. setTimeout(function rejectionCheck() {
  1308. this.pendingRejectionCheck = false;
  1309. var now = Date.now();
  1310. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1311. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1312. var unhandled = this.unhandledRejections[i].promise._value;
  1313. var msg = 'Unhandled rejection: ' + unhandled;
  1314. if (unhandled.stack) {
  1315. msg += '\n' + unhandled.stack;
  1316. }
  1317. warn(msg);
  1318. this.unhandledRejections.splice(i);
  1319. i--;
  1320. }
  1321. }
  1322. if (this.unhandledRejections.length) {
  1323. this.scheduleRejectionCheck();
  1324. }
  1325. }.bind(this), REJECTION_TIMEOUT);
  1326. }
  1327. };
  1328. function Promise(resolver) {
  1329. this._status = STATUS_PENDING;
  1330. this._handlers = [];
  1331. try {
  1332. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1333. } catch (e) {
  1334. this._reject(e);
  1335. }
  1336. }
  1337. /**
  1338. * Builds a promise that is resolved when all the passed in promises are
  1339. * resolved.
  1340. * @param {array} array of data and/or promises to wait for.
  1341. * @return {Promise} New dependant promise.
  1342. */
  1343. Promise.all = function Promise_all(promises) {
  1344. var resolveAll, rejectAll;
  1345. var deferred = new Promise(function (resolve, reject) {
  1346. resolveAll = resolve;
  1347. rejectAll = reject;
  1348. });
  1349. var unresolved = promises.length;
  1350. var results = [];
  1351. if (unresolved === 0) {
  1352. resolveAll(results);
  1353. return deferred;
  1354. }
  1355. function reject(reason) {
  1356. if (deferred._status === STATUS_REJECTED) {
  1357. return;
  1358. }
  1359. results = [];
  1360. rejectAll(reason);
  1361. }
  1362. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1363. var promise = promises[i];
  1364. var resolve = (function(i) {
  1365. return function(value) {
  1366. if (deferred._status === STATUS_REJECTED) {
  1367. return;
  1368. }
  1369. results[i] = value;
  1370. unresolved--;
  1371. if (unresolved === 0) {
  1372. resolveAll(results);
  1373. }
  1374. };
  1375. })(i);
  1376. if (Promise.isPromise(promise)) {
  1377. promise.then(resolve, reject);
  1378. } else {
  1379. resolve(promise);
  1380. }
  1381. }
  1382. return deferred;
  1383. };
  1384. /**
  1385. * Checks if the value is likely a promise (has a 'then' function).
  1386. * @return {boolean} true if value is thenable
  1387. */
  1388. Promise.isPromise = function Promise_isPromise(value) {
  1389. return value && typeof value.then === 'function';
  1390. };
  1391. /**
  1392. * Creates resolved promise
  1393. * @param value resolve value
  1394. * @returns {Promise}
  1395. */
  1396. Promise.resolve = function Promise_resolve(value) {
  1397. return new Promise(function (resolve) { resolve(value); });
  1398. };
  1399. /**
  1400. * Creates rejected promise
  1401. * @param reason rejection value
  1402. * @returns {Promise}
  1403. */
  1404. Promise.reject = function Promise_reject(reason) {
  1405. return new Promise(function (resolve, reject) { reject(reason); });
  1406. };
  1407. Promise.prototype = {
  1408. _status: null,
  1409. _value: null,
  1410. _handlers: null,
  1411. _unhandledRejection: null,
  1412. _updateStatus: function Promise__updateStatus(status, value) {
  1413. if (this._status === STATUS_RESOLVED ||
  1414. this._status === STATUS_REJECTED) {
  1415. return;
  1416. }
  1417. if (status === STATUS_RESOLVED &&
  1418. Promise.isPromise(value)) {
  1419. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1420. this._updateStatus.bind(this, STATUS_REJECTED));
  1421. return;
  1422. }
  1423. this._status = status;
  1424. this._value = value;
  1425. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1426. this._unhandledRejection = true;
  1427. HandlerManager.addUnhandledRejection(this);
  1428. }
  1429. HandlerManager.scheduleHandlers(this);
  1430. },
  1431. _resolve: function Promise_resolve(value) {
  1432. this._updateStatus(STATUS_RESOLVED, value);
  1433. },
  1434. _reject: function Promise_reject(reason) {
  1435. this._updateStatus(STATUS_REJECTED, reason);
  1436. },
  1437. then: function Promise_then(onResolve, onReject) {
  1438. var nextPromise = new Promise(function (resolve, reject) {
  1439. this.resolve = resolve;
  1440. this.reject = reject;
  1441. });
  1442. this._handlers.push({
  1443. thisPromise: this,
  1444. onResolve: onResolve,
  1445. onReject: onReject,
  1446. nextPromise: nextPromise
  1447. });
  1448. HandlerManager.scheduleHandlers(this);
  1449. return nextPromise;
  1450. },
  1451. catch: function Promise_catch(onReject) {
  1452. return this.then(undefined, onReject);
  1453. }
  1454. };
  1455. globalScope.Promise = Promise;
  1456. })();
  1457. var StatTimer = (function StatTimerClosure() {
  1458. function rpad(str, pad, length) {
  1459. while (str.length < length) {
  1460. str += pad;
  1461. }
  1462. return str;
  1463. }
  1464. function StatTimer() {
  1465. this.started = Object.create(null);
  1466. this.times = [];
  1467. this.enabled = true;
  1468. }
  1469. StatTimer.prototype = {
  1470. time: function StatTimer_time(name) {
  1471. if (!this.enabled) {
  1472. return;
  1473. }
  1474. if (name in this.started) {
  1475. warn('Timer is already running for ' + name);
  1476. }
  1477. this.started[name] = Date.now();
  1478. },
  1479. timeEnd: function StatTimer_timeEnd(name) {
  1480. if (!this.enabled) {
  1481. return;
  1482. }
  1483. if (!(name in this.started)) {
  1484. warn('Timer has not been started for ' + name);
  1485. }
  1486. this.times.push({
  1487. 'name': name,
  1488. 'start': this.started[name],
  1489. 'end': Date.now()
  1490. });
  1491. // Remove timer from started so it can be called again.
  1492. delete this.started[name];
  1493. },
  1494. toString: function StatTimer_toString() {
  1495. var i, ii;
  1496. var times = this.times;
  1497. var out = '';
  1498. // Find the longest name for padding purposes.
  1499. var longest = 0;
  1500. for (i = 0, ii = times.length; i < ii; ++i) {
  1501. var name = times[i]['name'];
  1502. if (name.length > longest) {
  1503. longest = name.length;
  1504. }
  1505. }
  1506. for (i = 0, ii = times.length; i < ii; ++i) {
  1507. var span = times[i];
  1508. var duration = span.end - span.start;
  1509. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1510. }
  1511. return out;
  1512. }
  1513. };
  1514. return StatTimer;
  1515. })();
  1516. PDFJS.createBlob = function createBlob(data, contentType) {
  1517. if (typeof Blob !== 'undefined') {
  1518. return new Blob([data], { type: contentType });
  1519. }
  1520. // Blob builder is deprecated in FF14 and removed in FF18.
  1521. var bb = new MozBlobBuilder();
  1522. bb.append(data);
  1523. return bb.getBlob(contentType);
  1524. };
  1525. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1526. // Blob/createObjectURL is not available, falling back to data schema.
  1527. var digits =
  1528. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1529. return function createObjectURL(data, contentType) {
  1530. if (!PDFJS.disableCreateObjectURL &&
  1531. typeof URL !== 'undefined' && URL.createObjectURL) {
  1532. var blob = PDFJS.createBlob(data, contentType);
  1533. return URL.createObjectURL(blob);
  1534. }
  1535. var buffer = 'data:' + contentType + ';base64,';
  1536. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1537. var b1 = data[i] & 0xFF;
  1538. var b2 = data[i + 1] & 0xFF;
  1539. var b3 = data[i + 2] & 0xFF;
  1540. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1541. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1542. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1543. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1544. }
  1545. return buffer;
  1546. };
  1547. })();
  1548. function MessageHandler(sourceName, targetName, comObj) {
  1549. this.sourceName = sourceName;
  1550. this.targetName = targetName;
  1551. this.comObj = comObj;
  1552. this.callbackIndex = 1;
  1553. this.postMessageTransfers = true;
  1554. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1555. var ah = this.actionHandler = Object.create(null);
  1556. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1557. var data = event.data;
  1558. if (data.targetName !== this.sourceName) {
  1559. return;
  1560. }
  1561. if (data.isReply) {
  1562. var callbackId = data.callbackId;
  1563. if (data.callbackId in callbacksCapabilities) {
  1564. var callback = callbacksCapabilities[callbackId];
  1565. delete callbacksCapabilities[callbackId];
  1566. if ('error' in data) {
  1567. callback.reject(data.error);
  1568. } else {
  1569. callback.resolve(data.data);
  1570. }
  1571. } else {
  1572. error('Cannot resolve callback ' + callbackId);
  1573. }
  1574. } else if (data.action in ah) {
  1575. var action = ah[data.action];
  1576. if (data.callbackId) {
  1577. var sourceName = this.sourceName;
  1578. var targetName = data.sourceName;
  1579. Promise.resolve().then(function () {
  1580. return action[0].call(action[1], data.data);
  1581. }).then(function (result) {
  1582. comObj.postMessage({
  1583. sourceName: sourceName,
  1584. targetName: targetName,
  1585. isReply: true,
  1586. callbackId: data.callbackId,
  1587. data: result
  1588. });
  1589. }, function (reason) {
  1590. if (reason instanceof Error) {
  1591. // Serialize error to avoid "DataCloneError"
  1592. reason = reason + '';
  1593. }
  1594. comObj.postMessage({
  1595. sourceName: sourceName,
  1596. targetName: targetName,
  1597. isReply: true,
  1598. callbackId: data.callbackId,
  1599. error: reason
  1600. });
  1601. });
  1602. } else {
  1603. action[0].call(action[1], data.data);
  1604. }
  1605. } else {
  1606. error('Unknown action from worker: ' + data.action);
  1607. }
  1608. }.bind(this);
  1609. comObj.addEventListener('message', this._onComObjOnMessage);
  1610. }
  1611. MessageHandler.prototype = {
  1612. on: function messageHandlerOn(actionName, handler, scope) {
  1613. var ah = this.actionHandler;
  1614. if (ah[actionName]) {
  1615. error('There is already an actionName called "' + actionName + '"');
  1616. }
  1617. ah[actionName] = [handler, scope];
  1618. },
  1619. /**
  1620. * Sends a message to the comObj to invoke the action with the supplied data.
  1621. * @param {String} actionName Action to call.
  1622. * @param {JSON} data JSON data to send.
  1623. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1624. */
  1625. send: function messageHandlerSend(actionName, data, transfers) {
  1626. var message = {
  1627. sourceName: this.sourceName,
  1628. targetName: this.targetName,
  1629. action: actionName,
  1630. data: data
  1631. };
  1632. this.postMessage(message, transfers);
  1633. },
  1634. /**
  1635. * Sends a message to the comObj to invoke the action with the supplied data.
  1636. * Expects that other side will callback with the response.
  1637. * @param {String} actionName Action to call.
  1638. * @param {JSON} data JSON data to send.
  1639. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1640. * @returns {Promise} Promise to be resolved with response data.
  1641. */
  1642. sendWithPromise:
  1643. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1644. var callbackId = this.callbackIndex++;
  1645. var message = {
  1646. sourceName: this.sourceName,
  1647. targetName: this.targetName,
  1648. action: actionName,
  1649. data: data,
  1650. callbackId: callbackId
  1651. };
  1652. var capability = createPromiseCapability();
  1653. this.callbacksCapabilities[callbackId] = capability;
  1654. try {
  1655. this.postMessage(message, transfers);
  1656. } catch (e) {
  1657. capability.reject(e);
  1658. }
  1659. return capability.promise;
  1660. },
  1661. /**
  1662. * Sends raw message to the comObj.
  1663. * @private
  1664. * @param message {Object} Raw message.
  1665. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1666. */
  1667. postMessage: function (message, transfers) {
  1668. if (transfers && this.postMessageTransfers) {
  1669. this.comObj.postMessage(message, transfers);
  1670. } else {
  1671. this.comObj.postMessage(message);
  1672. }
  1673. },
  1674. destroy: function () {
  1675. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1676. }
  1677. };
  1678. function loadJpegStream(id, imageUrl, objs) {
  1679. var img = new Image();
  1680. img.onload = (function loadJpegStream_onloadClosure() {
  1681. objs.resolve(id, img);
  1682. });
  1683. img.onerror = (function loadJpegStream_onerrorClosure() {
  1684. objs.resolve(id, null);
  1685. warn('Error during JPEG image loading');
  1686. });
  1687. img.src = imageUrl;
  1688. }
  1689. // Polyfill from https://github.com/Polymer/URL
  1690. /* Any copyright is dedicated to the Public Domain.
  1691. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1692. (function checkURLConstructor(scope) {
  1693. /* jshint ignore:start */
  1694. // feature detect for URL constructor
  1695. var hasWorkingUrl = false;
  1696. try {
  1697. if (typeof URL === 'function' &&
  1698. typeof URL.prototype === 'object' &&
  1699. ('origin' in URL.prototype)) {
  1700. var u = new URL('b', 'http://a');
  1701. u.pathname = 'c%20d';
  1702. hasWorkingUrl = u.href === 'http://a/c%20d';
  1703. }
  1704. } catch(e) { }
  1705. if (hasWorkingUrl)
  1706. return;
  1707. var relative = Object.create(null);
  1708. relative['ftp'] = 21;
  1709. relative['file'] = 0;
  1710. relative['gopher'] = 70;
  1711. relative['http'] = 80;
  1712. relative['https'] = 443;
  1713. relative['ws'] = 80;
  1714. relative['wss'] = 443;
  1715. var relativePathDotMapping = Object.create(null);
  1716. relativePathDotMapping['%2e'] = '.';
  1717. relativePathDotMapping['.%2e'] = '..';
  1718. relativePathDotMapping['%2e.'] = '..';
  1719. relativePathDotMapping['%2e%2e'] = '..';
  1720. function isRelativeScheme(scheme) {
  1721. return relative[scheme] !== undefined;
  1722. }
  1723. function invalid() {
  1724. clear.call(this);
  1725. this._isInvalid = true;
  1726. }
  1727. function IDNAToASCII(h) {
  1728. if ('' == h) {
  1729. invalid.call(this)
  1730. }
  1731. // XXX
  1732. return h.toLowerCase()
  1733. }
  1734. function percentEscape(c) {
  1735. var unicode = c.charCodeAt(0);
  1736. if (unicode > 0x20 &&
  1737. unicode < 0x7F &&
  1738. // " # < > ? `
  1739. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1
  1740. ) {
  1741. return c;
  1742. }
  1743. return encodeURIComponent(c);
  1744. }
  1745. function percentEscapeQuery(c) {
  1746. // XXX This actually needs to encode c using encoding and then
  1747. // convert the bytes one-by-one.
  1748. var unicode = c.charCodeAt(0);
  1749. if (unicode > 0x20 &&
  1750. unicode < 0x7F &&
  1751. // " # < > ` (do not escape '?')
  1752. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1
  1753. ) {
  1754. return c;
  1755. }
  1756. return encodeURIComponent(c);
  1757. }
  1758. var EOF = undefined,
  1759. ALPHA = /[a-zA-Z]/,
  1760. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1761. function parse(input, stateOverride, base) {
  1762. function err(message) {
  1763. errors.push(message)
  1764. }
  1765. var state = stateOverride || 'scheme start',
  1766. cursor = 0,
  1767. buffer = '',
  1768. seenAt = false,
  1769. seenBracket = false,
  1770. errors = [];
  1771. loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
  1772. var c = input[cursor];
  1773. switch (state) {
  1774. case 'scheme start':
  1775. if (c && ALPHA.test(c)) {
  1776. buffer += c.toLowerCase(); // ASCII-safe
  1777. state = 'scheme';
  1778. } else if (!stateOverride) {
  1779. buffer = '';
  1780. state = 'no scheme';
  1781. continue;
  1782. } else {
  1783. err('Invalid scheme.');
  1784. break loop;
  1785. }
  1786. break;
  1787. case 'scheme':
  1788. if (c && ALPHANUMERIC.test(c)) {
  1789. buffer += c.toLowerCase(); // ASCII-safe
  1790. } else if (':' == c) {
  1791. this._scheme = buffer;
  1792. buffer = '';
  1793. if (stateOverride) {
  1794. break loop;
  1795. }
  1796. if (isRelativeScheme(this._scheme)) {
  1797. this._isRelative = true;
  1798. }
  1799. if ('file' == this._scheme) {
  1800. state = 'relative';
  1801. } else if (this._isRelative && base && base._scheme == this._scheme) {
  1802. state = 'relative or authority';
  1803. } else if (this._isRelative) {
  1804. state = 'authority first slash';
  1805. } else {
  1806. state = 'scheme data';
  1807. }
  1808. } else if (!stateOverride) {
  1809. buffer = '';
  1810. cursor = 0;
  1811. state = 'no scheme';
  1812. continue;
  1813. } else if (EOF == c) {
  1814. break loop;
  1815. } else {
  1816. err('Code point not allowed in scheme: ' + c)
  1817. break loop;
  1818. }
  1819. break;
  1820. case 'scheme data':
  1821. if ('?' == c) {
  1822. this._query = '?';
  1823. state = 'query';
  1824. } else if ('#' == c) {
  1825. this._fragment = '#';
  1826. state = 'fragment';
  1827. } else {
  1828. // XXX error handling
  1829. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1830. this._schemeData += percentEscape(c);
  1831. }
  1832. }
  1833. break;
  1834. case 'no scheme':
  1835. if (!base || !(isRelativeScheme(base._scheme))) {
  1836. err('Missing scheme.');
  1837. invalid.call(this);
  1838. } else {
  1839. state = 'relative';
  1840. continue;
  1841. }
  1842. break;
  1843. case 'relative or authority':
  1844. if ('/' == c && '/' == input[cursor+1]) {
  1845. state = 'authority ignore slashes';
  1846. } else {
  1847. err('Expected /, got: ' + c);
  1848. state = 'relative';
  1849. continue
  1850. }
  1851. break;
  1852. case 'relative':
  1853. this._isRelative = true;
  1854. if ('file' != this._scheme)
  1855. this._scheme = base._scheme;
  1856. if (EOF == c) {
  1857. this._host = base._host;
  1858. this._port = base._port;
  1859. this._path = base._path.slice();
  1860. this._query = base._query;
  1861. this._username = base._username;
  1862. this._password = base._password;
  1863. break loop;
  1864. } else if ('/' == c || '\\' == c) {
  1865. if ('\\' == c)
  1866. err('\\ is an invalid code point.');
  1867. state = 'relative slash';
  1868. } else if ('?' == c) {
  1869. this._host = base._host;
  1870. this._port = base._port;
  1871. this._path = base._path.slice();
  1872. this._query = '?';
  1873. this._username = base._username;
  1874. this._password = base._password;
  1875. state = 'query';
  1876. } else if ('#' == c) {
  1877. this._host = base._host;
  1878. this._port = base._port;
  1879. this._path = base._path.slice();
  1880. this._query = base._query;
  1881. this._fragment = '#';
  1882. this._username = base._username;
  1883. this._password = base._password;
  1884. state = 'fragment';
  1885. } else {
  1886. var nextC = input[cursor+1]
  1887. var nextNextC = input[cursor+2]
  1888. if (
  1889. 'file' != this._scheme || !ALPHA.test(c) ||
  1890. (nextC != ':' && nextC != '|') ||
  1891. (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) {
  1892. this._host = base._host;
  1893. this._port = base._port;
  1894. this._username = base._username;
  1895. this._password = base._password;
  1896. this._path = base._path.slice();
  1897. this._path.pop();
  1898. }
  1899. state = 'relative path';
  1900. continue;
  1901. }
  1902. break;
  1903. case 'relative slash':
  1904. if ('/' == c || '\\' == c) {
  1905. if ('\\' == c) {
  1906. err('\\ is an invalid code point.');
  1907. }
  1908. if ('file' == this._scheme) {
  1909. state = 'file host';
  1910. } else {
  1911. state = 'authority ignore slashes';
  1912. }
  1913. } else {
  1914. if ('file' != this._scheme) {
  1915. this._host = base._host;
  1916. this._port = base._port;
  1917. this._username = base._username;
  1918. this._password = base._password;
  1919. }
  1920. state = 'relative path';
  1921. continue;
  1922. }
  1923. break;
  1924. case 'authority first slash':
  1925. if ('/' == c) {
  1926. state = 'authority second slash';
  1927. } else {
  1928. err("Expected '/', got: " + c);
  1929. state = 'authority ignore slashes';
  1930. continue;
  1931. }
  1932. break;
  1933. case 'authority second slash':
  1934. state = 'authority ignore slashes';
  1935. if ('/' != c) {
  1936. err("Expected '/', got: " + c);
  1937. continue;
  1938. }
  1939. break;
  1940. case 'authority ignore slashes':
  1941. if ('/' != c && '\\' != c) {
  1942. state = 'authority';
  1943. continue;
  1944. } else {
  1945. err('Expected authority, got: ' + c);
  1946. }
  1947. break;
  1948. case 'authority':
  1949. if ('@' == c) {
  1950. if (seenAt) {
  1951. err('@ already seen.');
  1952. buffer += '%40';
  1953. }
  1954. seenAt = true;
  1955. for (var i = 0; i < buffer.length; i++) {
  1956. var cp = buffer[i];
  1957. if ('\t' == cp || '\n' == cp || '\r' == cp) {
  1958. err('Invalid whitespace in authority.');
  1959. continue;
  1960. }
  1961. // XXX check URL code points
  1962. if (':' == cp && null === this._password) {
  1963. this._password = '';
  1964. continue;
  1965. }
  1966. var tempC = percentEscape(cp);
  1967. (null !== this._password) ? this._password += tempC : this._username += tempC;
  1968. }
  1969. buffer = '';
  1970. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1971. cursor -= buffer.length;
  1972. buffer = '';
  1973. state = 'host';
  1974. continue;
  1975. } else {
  1976. buffer += c;
  1977. }
  1978. break;
  1979. case 'file host':
  1980. if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1981. if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
  1982. state = 'relative path';
  1983. } else if (buffer.length == 0) {
  1984. state = 'relative path start';
  1985. } else {
  1986. this._host = IDNAToASCII.call(this, buffer);
  1987. buffer = '';
  1988. state = 'relative path start';
  1989. }
  1990. continue;
  1991. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1992. err('Invalid whitespace in file host.');
  1993. } else {
  1994. buffer += c;
  1995. }
  1996. break;
  1997. case 'host':
  1998. case 'hostname':
  1999. if (':' == c && !seenBracket) {
  2000. // XXX host parsing
  2001. this._host = IDNAToASCII.call(this, buffer);
  2002. buffer = '';
  2003. state = 'port';
  2004. if ('hostname' == stateOverride) {
  2005. break loop;
  2006. }
  2007. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  2008. this._host = IDNAToASCII.call(this, buffer);
  2009. buffer = '';
  2010. state = 'relative path start';
  2011. if (stateOverride) {
  2012. break loop;
  2013. }
  2014. continue;
  2015. } else if ('\t' != c && '\n' != c && '\r' != c) {
  2016. if ('[' == c) {
  2017. seenBracket = true;
  2018. } else if (']' == c) {
  2019. seenBracket = false;
  2020. }
  2021. buffer += c;
  2022. } else {
  2023. err('Invalid code point in host/hostname: ' + c);
  2024. }
  2025. break;
  2026. case 'port':
  2027. if (/[0-9]/.test(c)) {
  2028. buffer += c;
  2029. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
  2030. if ('' != buffer) {
  2031. var temp = parseInt(buffer, 10);
  2032. if (temp != relative[this._scheme]) {
  2033. this._port = temp + '';
  2034. }
  2035. buffer = '';
  2036. }
  2037. if (stateOverride) {
  2038. break loop;
  2039. }
  2040. state = 'relative path start';
  2041. continue;
  2042. } else if ('\t' == c || '\n' == c || '\r' == c) {
  2043. err('Invalid code point in port: ' + c);
  2044. } else {
  2045. invalid.call(this);
  2046. }
  2047. break;
  2048. case 'relative path start':
  2049. if ('\\' == c)
  2050. err("'\\' not allowed in path.");
  2051. state = 'relative path';
  2052. if ('/' != c && '\\' != c) {
  2053. continue;
  2054. }
  2055. break;
  2056. case 'relative path':
  2057. if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) {
  2058. if ('\\' == c) {
  2059. err('\\ not allowed in relative path.');
  2060. }
  2061. var tmp;
  2062. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  2063. buffer = tmp;
  2064. }
  2065. if ('..' == buffer) {
  2066. this._path.pop();
  2067. if ('/' != c && '\\' != c) {
  2068. this._path.push('');
  2069. }
  2070. } else if ('.' == buffer && '/' != c && '\\' != c) {
  2071. this._path.push('');
  2072. } else if ('.' != buffer) {
  2073. if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
  2074. buffer = buffer[0] + ':';
  2075. }
  2076. this._path.push(buffer);
  2077. }
  2078. buffer = '';
  2079. if ('?' == c) {
  2080. this._query = '?';
  2081. state = 'query';
  2082. } else if ('#' == c) {
  2083. this._fragment = '#';
  2084. state = 'fragment';
  2085. }
  2086. } else if ('\t' != c && '\n' != c && '\r' != c) {
  2087. buffer += percentEscape(c);
  2088. }
  2089. break;
  2090. case 'query':
  2091. if (!stateOverride && '#' == c) {
  2092. this._fragment = '#';
  2093. state = 'fragment';
  2094. } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  2095. this._query += percentEscapeQuery(c);
  2096. }
  2097. break;
  2098. case 'fragment':
  2099. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  2100. this._fragment += c;
  2101. }
  2102. break;
  2103. }
  2104. cursor++;
  2105. }
  2106. }
  2107. function clear() {
  2108. this._scheme = '';
  2109. this._schemeData = '';
  2110. this._username = '';
  2111. this._password = null;
  2112. this._host = '';
  2113. this._port = '';
  2114. this._path = [];
  2115. this._query = '';
  2116. this._fragment = '';
  2117. this._isInvalid = false;
  2118. this._isRelative = false;
  2119. }
  2120. // Does not process domain names or IP addresses.
  2121. // Does not handle encoding for the query parameter.
  2122. function jURL(url, base /* , encoding */) {
  2123. if (base !== undefined && !(base instanceof jURL))
  2124. base = new jURL(String(base));
  2125. this._url = url;
  2126. clear.call(this);
  2127. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2128. // encoding = encoding || 'utf-8'
  2129. parse.call(this, input, null, base);
  2130. }
  2131. jURL.prototype = {
  2132. toString: function() {
  2133. return this.href;
  2134. },
  2135. get href() {
  2136. if (this._isInvalid)
  2137. return this._url;
  2138. var authority = '';
  2139. if ('' != this._username || null != this._password) {
  2140. authority = this._username +
  2141. (null != this._password ? ':' + this._password : '') + '@';
  2142. }
  2143. return this.protocol +
  2144. (this._isRelative ? '//' + authority + this.host : '') +
  2145. this.pathname + this._query + this._fragment;
  2146. },
  2147. set href(href) {
  2148. clear.call(this);
  2149. parse.call(this, href);
  2150. },
  2151. get protocol() {
  2152. return this._scheme + ':';
  2153. },
  2154. set protocol(protocol) {
  2155. if (this._isInvalid)
  2156. return;
  2157. parse.call(this, protocol + ':', 'scheme start');
  2158. },
  2159. get host() {
  2160. return this._isInvalid ? '' : this._port ?
  2161. this._host + ':' + this._port : this._host;
  2162. },
  2163. set host(host) {
  2164. if (this._isInvalid || !this._isRelative)
  2165. return;
  2166. parse.call(this, host, 'host');
  2167. },
  2168. get hostname() {
  2169. return this._host;
  2170. },
  2171. set hostname(hostname) {
  2172. if (this._isInvalid || !this._isRelative)
  2173. return;
  2174. parse.call(this, hostname, 'hostname');
  2175. },
  2176. get port() {
  2177. return this._port;
  2178. },
  2179. set port(port) {
  2180. if (this._isInvalid || !this._isRelative)
  2181. return;
  2182. parse.call(this, port, 'port');
  2183. },
  2184. get pathname() {
  2185. return this._isInvalid ? '' : this._isRelative ?
  2186. '/' + this._path.join('/') : this._schemeData;
  2187. },
  2188. set pathname(pathname) {
  2189. if (this._isInvalid || !this._isRelative)
  2190. return;
  2191. this._path = [];
  2192. parse.call(this, pathname, 'relative path start');
  2193. },
  2194. get search() {
  2195. return this._isInvalid || !this._query || '?' == this._query ?
  2196. '' : this._query;
  2197. },
  2198. set search(search) {
  2199. if (this._isInvalid || !this._isRelative)
  2200. return;
  2201. this._query = '?';
  2202. if ('?' == search[0])
  2203. search = search.slice(1);
  2204. parse.call(this, search, 'query');
  2205. },
  2206. get hash() {
  2207. return this._isInvalid || !this._fragment || '#' == this._fragment ?
  2208. '' : this._fragment;
  2209. },
  2210. set hash(hash) {
  2211. if (this._isInvalid)
  2212. return;
  2213. this._fragment = '#';
  2214. if ('#' == hash[0])
  2215. hash = hash.slice(1);
  2216. parse.call(this, hash, 'fragment');
  2217. },
  2218. get origin() {
  2219. var host;
  2220. if (this._isInvalid || !this._scheme) {
  2221. return '';
  2222. }
  2223. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2224. // Gecko throws error for "data://"
  2225. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2226. // Gecko returns String("") for file: mailto:
  2227. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2228. switch (this._scheme) {
  2229. case 'data':
  2230. case 'file':
  2231. case 'javascript':
  2232. case 'mailto':
  2233. return 'null';
  2234. }
  2235. host = this.host;
  2236. if (!host) {
  2237. return '';
  2238. }
  2239. return this._scheme + '://' + host;
  2240. }
  2241. };
  2242. // Copy over the static methods
  2243. var OriginalURL = scope.URL;
  2244. if (OriginalURL) {
  2245. jURL.createObjectURL = function(blob) {
  2246. // IE extension allows a second optional options argument.
  2247. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2248. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2249. };
  2250. jURL.revokeObjectURL = function(url) {
  2251. OriginalURL.revokeObjectURL(url);
  2252. };
  2253. }
  2254. scope.URL = jURL;
  2255. /* jshint ignore:end */
  2256. })(globalScope);
  2257. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2258. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2259. exports.OPS = OPS;
  2260. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2261. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2262. exports.AnnotationFlag = AnnotationFlag;
  2263. exports.AnnotationType = AnnotationType;
  2264. exports.FontType = FontType;
  2265. exports.ImageKind = ImageKind;
  2266. exports.InvalidPDFException = InvalidPDFException;
  2267. exports.LinkTarget = LinkTarget;
  2268. exports.LinkTargetStringMap = LinkTargetStringMap;
  2269. exports.MessageHandler = MessageHandler;
  2270. exports.MissingDataException = MissingDataException;
  2271. exports.MissingPDFException = MissingPDFException;
  2272. exports.NotImplementedException = NotImplementedException;
  2273. exports.PasswordException = PasswordException;
  2274. exports.PasswordResponses = PasswordResponses;
  2275. exports.StatTimer = StatTimer;
  2276. exports.StreamType = StreamType;
  2277. exports.TextRenderingMode = TextRenderingMode;
  2278. exports.UnexpectedResponseException = UnexpectedResponseException;
  2279. exports.UnknownErrorException = UnknownErrorException;
  2280. exports.Util = Util;
  2281. exports.XRefParseException = XRefParseException;
  2282. exports.arrayByteLength = arrayByteLength;
  2283. exports.arraysToBytes = arraysToBytes;
  2284. exports.assert = assert;
  2285. exports.bytesToString = bytesToString;
  2286. exports.combineUrl = combineUrl;
  2287. exports.createPromiseCapability = createPromiseCapability;
  2288. exports.deprecated = deprecated;
  2289. exports.error = error;
  2290. exports.getFilenameFromUrl = getFilenameFromUrl;
  2291. exports.getLookupTableFactory = getLookupTableFactory;
  2292. exports.info = info;
  2293. exports.isArray = isArray;
  2294. exports.isArrayBuffer = isArrayBuffer;
  2295. exports.isBool = isBool;
  2296. exports.isEmptyObj = isEmptyObj;
  2297. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2298. exports.isInt = isInt;
  2299. exports.isNum = isNum;
  2300. exports.isString = isString;
  2301. exports.isSameOrigin = isSameOrigin;
  2302. exports.isValidUrl = isValidUrl;
  2303. exports.addLinkAttributes = addLinkAttributes;
  2304. exports.loadJpegStream = loadJpegStream;
  2305. exports.log2 = log2;
  2306. exports.readInt8 = readInt8;
  2307. exports.readUint16 = readUint16;
  2308. exports.readUint32 = readUint32;
  2309. exports.removeNullCharacters = removeNullCharacters;
  2310. exports.shadow = shadow;
  2311. exports.string32 = string32;
  2312. exports.stringToBytes = stringToBytes;
  2313. exports.stringToPDFString = stringToPDFString;
  2314. exports.stringToUTF8String = stringToUTF8String;
  2315. exports.utf8StringToString = utf8StringToString;
  2316. exports.warn = warn;
  2317. }));
  2318. (function (root, factory) {
  2319. {
  2320. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  2321. root.pdfjsDisplayDOMUtils);
  2322. }
  2323. }(this, function (exports, sharedUtil, displayDOMUtils) {
  2324. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  2325. var AnnotationType = sharedUtil.AnnotationType;
  2326. var Util = sharedUtil.Util;
  2327. var addLinkAttributes = sharedUtil.addLinkAttributes;
  2328. var getFilenameFromUrl = sharedUtil.getFilenameFromUrl;
  2329. var warn = sharedUtil.warn;
  2330. var CustomStyle = displayDOMUtils.CustomStyle;
  2331. /**
  2332. * @typedef {Object} AnnotationElementParameters
  2333. * @property {Object} data
  2334. * @property {HTMLDivElement} layer
  2335. * @property {PDFPage} page
  2336. * @property {PageViewport} viewport
  2337. * @property {IPDFLinkService} linkService
  2338. * @property {DownloadManager} downloadManager
  2339. */
  2340. /**
  2341. * @class
  2342. * @alias AnnotationElementFactory
  2343. */
  2344. function AnnotationElementFactory() {}
  2345. AnnotationElementFactory.prototype =
  2346. /** @lends AnnotationElementFactory.prototype */ {
  2347. /**
  2348. * @param {AnnotationElementParameters} parameters
  2349. * @returns {AnnotationElement}
  2350. */
  2351. create: function AnnotationElementFactory_create(parameters) {
  2352. var subtype = parameters.data.annotationType;
  2353. switch (subtype) {
  2354. case AnnotationType.LINK:
  2355. return new LinkAnnotationElement(parameters);
  2356. case AnnotationType.TEXT:
  2357. return new TextAnnotationElement(parameters);
  2358. case AnnotationType.WIDGET:
  2359. return new WidgetAnnotationElement(parameters);
  2360. case AnnotationType.POPUP:
  2361. return new PopupAnnotationElement(parameters);
  2362. case AnnotationType.HIGHLIGHT:
  2363. return new HighlightAnnotationElement(parameters);
  2364. case AnnotationType.UNDERLINE:
  2365. return new UnderlineAnnotationElement(parameters);
  2366. case AnnotationType.SQUIGGLY:
  2367. return new SquigglyAnnotationElement(parameters);
  2368. case AnnotationType.STRIKEOUT:
  2369. return new StrikeOutAnnotationElement(parameters);
  2370. case AnnotationType.FILEATTACHMENT:
  2371. return new FileAttachmentAnnotationElement(parameters);
  2372. default:
  2373. return new AnnotationElement(parameters);
  2374. }
  2375. }
  2376. };
  2377. /**
  2378. * @class
  2379. * @alias AnnotationElement
  2380. */
  2381. var AnnotationElement = (function AnnotationElementClosure() {
  2382. function AnnotationElement(parameters, isRenderable) {
  2383. this.isRenderable = isRenderable || false;
  2384. this.data = parameters.data;
  2385. this.layer = parameters.layer;
  2386. this.page = parameters.page;
  2387. this.viewport = parameters.viewport;
  2388. this.linkService = parameters.linkService;
  2389. this.downloadManager = parameters.downloadManager;
  2390. if (isRenderable) {
  2391. this.container = this._createContainer();
  2392. }
  2393. }
  2394. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  2395. /**
  2396. * Create an empty container for the annotation's HTML element.
  2397. *
  2398. * @private
  2399. * @memberof AnnotationElement
  2400. * @returns {HTMLSectionElement}
  2401. */
  2402. _createContainer: function AnnotationElement_createContainer() {
  2403. var data = this.data, page = this.page, viewport = this.viewport;
  2404. var container = document.createElement('section');
  2405. var width = data.rect[2] - data.rect[0];
  2406. var height = data.rect[3] - data.rect[1];
  2407. container.setAttribute('data-annotation-id', data.id);
  2408. // Do *not* modify `data.rect`, since that will corrupt the annotation
  2409. // position on subsequent calls to `_createContainer` (see issue 6804).
  2410. var rect = Util.normalizeRect([
  2411. data.rect[0],
  2412. page.view[3] - data.rect[1] + page.view[1],
  2413. data.rect[2],
  2414. page.view[3] - data.rect[3] + page.view[1]
  2415. ]);
  2416. CustomStyle.setProp('transform', container,
  2417. 'matrix(' + viewport.transform.join(',') + ')');
  2418. CustomStyle.setProp('transformOrigin', container,
  2419. -rect[0] + 'px ' + -rect[1] + 'px');
  2420. if (data.borderStyle.width > 0) {
  2421. container.style.borderWidth = data.borderStyle.width + 'px';
  2422. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  2423. // Underline styles only have a bottom border, so we do not need
  2424. // to adjust for all borders. This yields a similar result as
  2425. // Adobe Acrobat/Reader.
  2426. width = width - 2 * data.borderStyle.width;
  2427. height = height - 2 * data.borderStyle.width;
  2428. }
  2429. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  2430. var verticalRadius = data.borderStyle.verticalCornerRadius;
  2431. if (horizontalRadius > 0 || verticalRadius > 0) {
  2432. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  2433. CustomStyle.setProp('borderRadius', container, radius);
  2434. }
  2435. switch (data.borderStyle.style) {
  2436. case AnnotationBorderStyleType.SOLID:
  2437. container.style.borderStyle = 'solid';
  2438. break;
  2439. case AnnotationBorderStyleType.DASHED:
  2440. container.style.borderStyle = 'dashed';
  2441. break;
  2442. case AnnotationBorderStyleType.BEVELED:
  2443. warn('Unimplemented border style: beveled');
  2444. break;
  2445. case AnnotationBorderStyleType.INSET:
  2446. warn('Unimplemented border style: inset');
  2447. break;
  2448. case AnnotationBorderStyleType.UNDERLINE:
  2449. container.style.borderBottomStyle = 'solid';
  2450. break;
  2451. default:
  2452. break;
  2453. }
  2454. if (data.color) {
  2455. container.style.borderColor =
  2456. Util.makeCssRgb(data.color[0] | 0,
  2457. data.color[1] | 0,
  2458. data.color[2] | 0);
  2459. } else {
  2460. // Transparent (invisible) border, so do not draw it at all.
  2461. container.style.borderWidth = 0;
  2462. }
  2463. }
  2464. container.style.left = rect[0] + 'px';
  2465. container.style.top = rect[1] + 'px';
  2466. container.style.width = width + 'px';
  2467. container.style.height = height + 'px';
  2468. return container;
  2469. },
  2470. /**
  2471. * Create a popup for the annotation's HTML element. This is used for
  2472. * annotations that do not have a Popup entry in the dictionary, but
  2473. * are of a type that works with popups (such as Highlight annotations).
  2474. *
  2475. * @private
  2476. * @param {HTMLSectionElement} container
  2477. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  2478. * @param {Object} data
  2479. * @memberof AnnotationElement
  2480. */
  2481. _createPopup:
  2482. function AnnotationElement_createPopup(container, trigger, data) {
  2483. // If no trigger element is specified, create it.
  2484. if (!trigger) {
  2485. trigger = document.createElement('div');
  2486. trigger.style.height = container.style.height;
  2487. trigger.style.width = container.style.width;
  2488. container.appendChild(trigger);
  2489. }
  2490. var popupElement = new PopupElement({
  2491. container: container,
  2492. trigger: trigger,
  2493. color: data.color,
  2494. title: data.title,
  2495. contents: data.contents,
  2496. hideWrapper: true
  2497. });
  2498. var popup = popupElement.render();
  2499. // Position the popup next to the annotation's container.
  2500. popup.style.left = container.style.width;
  2501. container.appendChild(popup);
  2502. },
  2503. /**
  2504. * Render the annotation's HTML element in the empty container.
  2505. *
  2506. * @public
  2507. * @memberof AnnotationElement
  2508. */
  2509. render: function AnnotationElement_render() {
  2510. throw new Error('Abstract method AnnotationElement.render called');
  2511. }
  2512. };
  2513. return AnnotationElement;
  2514. })();
  2515. /**
  2516. * @class
  2517. * @alias LinkAnnotationElement
  2518. */
  2519. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  2520. function LinkAnnotationElement(parameters) {
  2521. AnnotationElement.call(this, parameters, true);
  2522. }
  2523. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  2524. /**
  2525. * Render the link annotation's HTML element in the empty container.
  2526. *
  2527. * @public
  2528. * @memberof LinkAnnotationElement
  2529. * @returns {HTMLSectionElement}
  2530. */
  2531. render: function LinkAnnotationElement_render() {
  2532. this.container.className = 'linkAnnotation';
  2533. var link = document.createElement('a');
  2534. addLinkAttributes(link, { url: this.data.url });
  2535. if (!this.data.url) {
  2536. if (this.data.action) {
  2537. this._bindNamedAction(link, this.data.action);
  2538. } else {
  2539. this._bindLink(link, ('dest' in this.data) ? this.data.dest : null);
  2540. }
  2541. }
  2542. this.container.appendChild(link);
  2543. return this.container;
  2544. },
  2545. /**
  2546. * Bind internal links to the link element.
  2547. *
  2548. * @private
  2549. * @param {Object} link
  2550. * @param {Object} destination
  2551. * @memberof LinkAnnotationElement
  2552. */
  2553. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  2554. var self = this;
  2555. link.href = this.linkService.getDestinationHash(destination);
  2556. link.onclick = function() {
  2557. if (destination) {
  2558. self.linkService.navigateTo(destination);
  2559. }
  2560. return false;
  2561. };
  2562. if (destination) {
  2563. link.className = 'internalLink';
  2564. }
  2565. },
  2566. /**
  2567. * Bind named actions to the link element.
  2568. *
  2569. * @private
  2570. * @param {Object} link
  2571. * @param {Object} action
  2572. * @memberof LinkAnnotationElement
  2573. */
  2574. _bindNamedAction:
  2575. function LinkAnnotationElement_bindNamedAction(link, action) {
  2576. var self = this;
  2577. link.href = this.linkService.getAnchorUrl('');
  2578. link.onclick = function() {
  2579. self.linkService.executeNamedAction(action);
  2580. return false;
  2581. };
  2582. link.className = 'internalLink';
  2583. }
  2584. });
  2585. return LinkAnnotationElement;
  2586. })();
  2587. /**
  2588. * @class
  2589. * @alias TextAnnotationElement
  2590. */
  2591. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  2592. function TextAnnotationElement(parameters) {
  2593. var isRenderable = !!(parameters.data.hasPopup ||
  2594. parameters.data.title || parameters.data.contents);
  2595. AnnotationElement.call(this, parameters, isRenderable);
  2596. }
  2597. Util.inherit(TextAnnotationElement, AnnotationElement, {
  2598. /**
  2599. * Render the text annotation's HTML element in the empty container.
  2600. *
  2601. * @public
  2602. * @memberof TextAnnotationElement
  2603. * @returns {HTMLSectionElement}
  2604. */
  2605. render: function TextAnnotationElement_render() {
  2606. this.container.className = 'textAnnotation';
  2607. var image = document.createElement('img');
  2608. image.style.height = this.container.style.height;
  2609. image.style.width = this.container.style.width;
  2610. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  2611. this.data.name.toLowerCase() + '.svg';
  2612. image.alt = '[{{type}} Annotation]';
  2613. image.dataset.l10nId = 'text_annotation_type';
  2614. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  2615. if (!this.data.hasPopup) {
  2616. this._createPopup(this.container, image, this.data);
  2617. }
  2618. this.container.appendChild(image);
  2619. return this.container;
  2620. }
  2621. });
  2622. return TextAnnotationElement;
  2623. })();
  2624. /**
  2625. * @class
  2626. * @alias WidgetAnnotationElement
  2627. */
  2628. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  2629. function WidgetAnnotationElement(parameters) {
  2630. var isRenderable = !parameters.data.hasAppearance &&
  2631. !!parameters.data.fieldValue;
  2632. AnnotationElement.call(this, parameters, isRenderable);
  2633. }
  2634. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  2635. /**
  2636. * Render the widget annotation's HTML element in the empty container.
  2637. *
  2638. * @public
  2639. * @memberof WidgetAnnotationElement
  2640. * @returns {HTMLSectionElement}
  2641. */
  2642. render: function WidgetAnnotationElement_render() {
  2643. var content = document.createElement('div');
  2644. content.textContent = this.data.fieldValue;
  2645. var textAlignment = this.data.textAlignment;
  2646. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  2647. content.style.verticalAlign = 'middle';
  2648. content.style.display = 'table-cell';
  2649. var font = (this.data.fontRefName ?
  2650. this.page.commonObjs.getData(this.data.fontRefName) : null);
  2651. this._setTextStyle(content, font);
  2652. this.container.appendChild(content);
  2653. return this.container;
  2654. },
  2655. /**
  2656. * Apply text styles to the text in the element.
  2657. *
  2658. * @private
  2659. * @param {HTMLDivElement} element
  2660. * @param {Object} font
  2661. * @memberof WidgetAnnotationElement
  2662. */
  2663. _setTextStyle:
  2664. function WidgetAnnotationElement_setTextStyle(element, font) {
  2665. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  2666. var style = element.style;
  2667. style.fontSize = this.data.fontSize + 'px';
  2668. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  2669. if (!font) {
  2670. return;
  2671. }
  2672. style.fontWeight = (font.black ?
  2673. (font.bold ? '900' : 'bold') :
  2674. (font.bold ? 'bold' : 'normal'));
  2675. style.fontStyle = (font.italic ? 'italic' : 'normal');
  2676. // Use a reasonable default font if the font doesn't specify a fallback.
  2677. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  2678. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  2679. style.fontFamily = fontFamily + fallbackName;
  2680. }
  2681. });
  2682. return WidgetAnnotationElement;
  2683. })();
  2684. /**
  2685. * @class
  2686. * @alias PopupAnnotationElement
  2687. */
  2688. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  2689. function PopupAnnotationElement(parameters) {
  2690. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  2691. AnnotationElement.call(this, parameters, isRenderable);
  2692. }
  2693. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  2694. /**
  2695. * Render the popup annotation's HTML element in the empty container.
  2696. *
  2697. * @public
  2698. * @memberof PopupAnnotationElement
  2699. * @returns {HTMLSectionElement}
  2700. */
  2701. render: function PopupAnnotationElement_render() {
  2702. this.container.className = 'popupAnnotation';
  2703. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  2704. var parentElement = this.layer.querySelector(selector);
  2705. if (!parentElement) {
  2706. return this.container;
  2707. }
  2708. var popup = new PopupElement({
  2709. container: this.container,
  2710. trigger: parentElement,
  2711. color: this.data.color,
  2712. title: this.data.title,
  2713. contents: this.data.contents
  2714. });
  2715. // Position the popup next to the parent annotation's container.
  2716. // PDF viewers ignore a popup annotation's rectangle.
  2717. var parentLeft = parseFloat(parentElement.style.left);
  2718. var parentWidth = parseFloat(parentElement.style.width);
  2719. CustomStyle.setProp('transformOrigin', this.container,
  2720. -(parentLeft + parentWidth) + 'px -' +
  2721. parentElement.style.top);
  2722. this.container.style.left = (parentLeft + parentWidth) + 'px';
  2723. this.container.appendChild(popup.render());
  2724. return this.container;
  2725. }
  2726. });
  2727. return PopupAnnotationElement;
  2728. })();
  2729. /**
  2730. * @class
  2731. * @alias PopupElement
  2732. */
  2733. var PopupElement = (function PopupElementClosure() {
  2734. var BACKGROUND_ENLIGHT = 0.7;
  2735. function PopupElement(parameters) {
  2736. this.container = parameters.container;
  2737. this.trigger = parameters.trigger;
  2738. this.color = parameters.color;
  2739. this.title = parameters.title;
  2740. this.contents = parameters.contents;
  2741. this.hideWrapper = parameters.hideWrapper || false;
  2742. this.pinned = false;
  2743. }
  2744. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  2745. /**
  2746. * Render the popup's HTML element.
  2747. *
  2748. * @public
  2749. * @memberof PopupElement
  2750. * @returns {HTMLSectionElement}
  2751. */
  2752. render: function PopupElement_render() {
  2753. var wrapper = document.createElement('div');
  2754. wrapper.className = 'popupWrapper';
  2755. // For Popup annotations we hide the entire section because it contains
  2756. // only the popup. However, for Text annotations without a separate Popup
  2757. // annotation, we cannot hide the entire container as the image would
  2758. // disappear too. In that special case, hiding the wrapper suffices.
  2759. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  2760. this.hideElement.setAttribute('hidden', true);
  2761. var popup = document.createElement('div');
  2762. popup.className = 'popup';
  2763. var color = this.color;
  2764. if (color) {
  2765. // Enlighten the color.
  2766. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  2767. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  2768. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  2769. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  2770. }
  2771. var contents = this._formatContents(this.contents);
  2772. var title = document.createElement('h1');
  2773. title.textContent = this.title;
  2774. // Attach the event listeners to the trigger element.
  2775. this.trigger.addEventListener('click', this._toggle.bind(this));
  2776. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  2777. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  2778. popup.addEventListener('click', this._hide.bind(this, true));
  2779. popup.appendChild(title);
  2780. popup.appendChild(contents);
  2781. wrapper.appendChild(popup);
  2782. return wrapper;
  2783. },
  2784. /**
  2785. * Format the contents of the popup by adding newlines where necessary.
  2786. *
  2787. * @private
  2788. * @param {string} contents
  2789. * @memberof PopupElement
  2790. * @returns {HTMLParagraphElement}
  2791. */
  2792. _formatContents: function PopupElement_formatContents(contents) {
  2793. var p = document.createElement('p');
  2794. var lines = contents.split(/(?:\r\n?|\n)/);
  2795. for (var i = 0, ii = lines.length; i < ii; ++i) {
  2796. var line = lines[i];
  2797. p.appendChild(document.createTextNode(line));
  2798. if (i < (ii - 1)) {
  2799. p.appendChild(document.createElement('br'));
  2800. }
  2801. }
  2802. return p;
  2803. },
  2804. /**
  2805. * Toggle the visibility of the popup.
  2806. *
  2807. * @private
  2808. * @memberof PopupElement
  2809. */
  2810. _toggle: function PopupElement_toggle() {
  2811. if (this.pinned) {
  2812. this._hide(true);
  2813. } else {
  2814. this._show(true);
  2815. }
  2816. },
  2817. /**
  2818. * Show the popup.
  2819. *
  2820. * @private
  2821. * @param {boolean} pin
  2822. * @memberof PopupElement
  2823. */
  2824. _show: function PopupElement_show(pin) {
  2825. if (pin) {
  2826. this.pinned = true;
  2827. }
  2828. if (this.hideElement.hasAttribute('hidden')) {
  2829. this.hideElement.removeAttribute('hidden');
  2830. this.container.style.zIndex += 1;
  2831. }
  2832. },
  2833. /**
  2834. * Hide the popup.
  2835. *
  2836. * @private
  2837. * @param {boolean} unpin
  2838. * @memberof PopupElement
  2839. */
  2840. _hide: function PopupElement_hide(unpin) {
  2841. if (unpin) {
  2842. this.pinned = false;
  2843. }
  2844. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  2845. this.hideElement.setAttribute('hidden', true);
  2846. this.container.style.zIndex -= 1;
  2847. }
  2848. }
  2849. };
  2850. return PopupElement;
  2851. })();
  2852. /**
  2853. * @class
  2854. * @alias HighlightAnnotationElement
  2855. */
  2856. var HighlightAnnotationElement = (
  2857. function HighlightAnnotationElementClosure() {
  2858. function HighlightAnnotationElement(parameters) {
  2859. var isRenderable = !!(parameters.data.hasPopup ||
  2860. parameters.data.title || parameters.data.contents);
  2861. AnnotationElement.call(this, parameters, isRenderable);
  2862. }
  2863. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  2864. /**
  2865. * Render the highlight annotation's HTML element in the empty container.
  2866. *
  2867. * @public
  2868. * @memberof HighlightAnnotationElement
  2869. * @returns {HTMLSectionElement}
  2870. */
  2871. render: function HighlightAnnotationElement_render() {
  2872. this.container.className = 'highlightAnnotation';
  2873. if (!this.data.hasPopup) {
  2874. this._createPopup(this.container, null, this.data);
  2875. }
  2876. return this.container;
  2877. }
  2878. });
  2879. return HighlightAnnotationElement;
  2880. })();
  2881. /**
  2882. * @class
  2883. * @alias UnderlineAnnotationElement
  2884. */
  2885. var UnderlineAnnotationElement = (
  2886. function UnderlineAnnotationElementClosure() {
  2887. function UnderlineAnnotationElement(parameters) {
  2888. var isRenderable = !!(parameters.data.hasPopup ||
  2889. parameters.data.title || parameters.data.contents);
  2890. AnnotationElement.call(this, parameters, isRenderable);
  2891. }
  2892. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  2893. /**
  2894. * Render the underline annotation's HTML element in the empty container.
  2895. *
  2896. * @public
  2897. * @memberof UnderlineAnnotationElement
  2898. * @returns {HTMLSectionElement}
  2899. */
  2900. render: function UnderlineAnnotationElement_render() {
  2901. this.container.className = 'underlineAnnotation';
  2902. if (!this.data.hasPopup) {
  2903. this._createPopup(this.container, null, this.data);
  2904. }
  2905. return this.container;
  2906. }
  2907. });
  2908. return UnderlineAnnotationElement;
  2909. })();
  2910. /**
  2911. * @class
  2912. * @alias SquigglyAnnotationElement
  2913. */
  2914. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  2915. function SquigglyAnnotationElement(parameters) {
  2916. var isRenderable = !!(parameters.data.hasPopup ||
  2917. parameters.data.title || parameters.data.contents);
  2918. AnnotationElement.call(this, parameters, isRenderable);
  2919. }
  2920. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  2921. /**
  2922. * Render the squiggly annotation's HTML element in the empty container.
  2923. *
  2924. * @public
  2925. * @memberof SquigglyAnnotationElement
  2926. * @returns {HTMLSectionElement}
  2927. */
  2928. render: function SquigglyAnnotationElement_render() {
  2929. this.container.className = 'squigglyAnnotation';
  2930. if (!this.data.hasPopup) {
  2931. this._createPopup(this.container, null, this.data);
  2932. }
  2933. return this.container;
  2934. }
  2935. });
  2936. return SquigglyAnnotationElement;
  2937. })();
  2938. /**
  2939. * @class
  2940. * @alias StrikeOutAnnotationElement
  2941. */
  2942. var StrikeOutAnnotationElement = (
  2943. function StrikeOutAnnotationElementClosure() {
  2944. function StrikeOutAnnotationElement(parameters) {
  2945. var isRenderable = !!(parameters.data.hasPopup ||
  2946. parameters.data.title || parameters.data.contents);
  2947. AnnotationElement.call(this, parameters, isRenderable);
  2948. }
  2949. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  2950. /**
  2951. * Render the strikeout annotation's HTML element in the empty container.
  2952. *
  2953. * @public
  2954. * @memberof StrikeOutAnnotationElement
  2955. * @returns {HTMLSectionElement}
  2956. */
  2957. render: function StrikeOutAnnotationElement_render() {
  2958. this.container.className = 'strikeoutAnnotation';
  2959. if (!this.data.hasPopup) {
  2960. this._createPopup(this.container, null, this.data);
  2961. }
  2962. return this.container;
  2963. }
  2964. });
  2965. return StrikeOutAnnotationElement;
  2966. })();
  2967. /**
  2968. * @class
  2969. * @alias FileAttachmentAnnotationElement
  2970. */
  2971. var FileAttachmentAnnotationElement = (
  2972. function FileAttachmentAnnotationElementClosure() {
  2973. function FileAttachmentAnnotationElement(parameters) {
  2974. AnnotationElement.call(this, parameters, true);
  2975. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  2976. this.content = parameters.data.file.content;
  2977. }
  2978. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  2979. /**
  2980. * Render the file attachment annotation's HTML element in the empty
  2981. * container.
  2982. *
  2983. * @public
  2984. * @memberof FileAttachmentAnnotationElement
  2985. * @returns {HTMLSectionElement}
  2986. */
  2987. render: function FileAttachmentAnnotationElement_render() {
  2988. this.container.className = 'fileAttachmentAnnotation';
  2989. var trigger = document.createElement('div');
  2990. trigger.style.height = this.container.style.height;
  2991. trigger.style.width = this.container.style.width;
  2992. trigger.addEventListener('dblclick', this._download.bind(this));
  2993. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  2994. this._createPopup(this.container, trigger, this.data);
  2995. }
  2996. this.container.appendChild(trigger);
  2997. return this.container;
  2998. },
  2999. /**
  3000. * Download the file attachment associated with this annotation.
  3001. *
  3002. * @private
  3003. * @memberof FileAttachmentAnnotationElement
  3004. */
  3005. _download: function FileAttachmentAnnotationElement_download() {
  3006. if (!this.downloadManager) {
  3007. warn('Download cannot be started due to unavailable download manager');
  3008. return;
  3009. }
  3010. this.downloadManager.downloadData(this.content, this.filename, '');
  3011. }
  3012. });
  3013. return FileAttachmentAnnotationElement;
  3014. })();
  3015. /**
  3016. * @typedef {Object} AnnotationLayerParameters
  3017. * @property {PageViewport} viewport
  3018. * @property {HTMLDivElement} div
  3019. * @property {Array} annotations
  3020. * @property {PDFPage} page
  3021. * @property {IPDFLinkService} linkService
  3022. */
  3023. /**
  3024. * @class
  3025. * @alias AnnotationLayer
  3026. */
  3027. var AnnotationLayer = (function AnnotationLayerClosure() {
  3028. return {
  3029. /**
  3030. * Render a new annotation layer with all annotation elements.
  3031. *
  3032. * @public
  3033. * @param {AnnotationLayerParameters} parameters
  3034. * @memberof AnnotationLayer
  3035. */
  3036. render: function AnnotationLayer_render(parameters) {
  3037. var annotationElementFactory = new AnnotationElementFactory();
  3038. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  3039. var data = parameters.annotations[i];
  3040. if (!data) {
  3041. continue;
  3042. }
  3043. var properties = {
  3044. data: data,
  3045. layer: parameters.div,
  3046. page: parameters.page,
  3047. viewport: parameters.viewport,
  3048. linkService: parameters.linkService,
  3049. downloadManager: parameters.downloadManager
  3050. };
  3051. var element = annotationElementFactory.create(properties);
  3052. if (element.isRenderable) {
  3053. parameters.div.appendChild(element.render());
  3054. }
  3055. }
  3056. },
  3057. /**
  3058. * Update the annotation elements on existing annotation layer.
  3059. *
  3060. * @public
  3061. * @param {AnnotationLayerParameters} parameters
  3062. * @memberof AnnotationLayer
  3063. */
  3064. update: function AnnotationLayer_update(parameters) {
  3065. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  3066. var data = parameters.annotations[i];
  3067. var element = parameters.div.querySelector(
  3068. '[data-annotation-id="' + data.id + '"]');
  3069. if (element) {
  3070. CustomStyle.setProp('transform', element,
  3071. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  3072. }
  3073. }
  3074. parameters.div.removeAttribute('hidden');
  3075. }
  3076. };
  3077. })();
  3078. PDFJS.AnnotationLayer = AnnotationLayer;
  3079. exports.AnnotationLayer = AnnotationLayer;
  3080. }));
  3081. (function (root, factory) {
  3082. {
  3083. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil,
  3084. root.pdfjsSharedGlobal);
  3085. }
  3086. }(this, function (exports, sharedUtil, sharedGlobal) {
  3087. var assert = sharedUtil.assert;
  3088. var bytesToString = sharedUtil.bytesToString;
  3089. var string32 = sharedUtil.string32;
  3090. var shadow = sharedUtil.shadow;
  3091. var warn = sharedUtil.warn;
  3092. var PDFJS = sharedGlobal.PDFJS;
  3093. var globalScope = sharedGlobal.globalScope;
  3094. var isWorker = sharedGlobal.isWorker;
  3095. function FontLoader(docId) {
  3096. this.docId = docId;
  3097. this.styleElement = null;
  3098. this.nativeFontFaces = [];
  3099. this.loadTestFontId = 0;
  3100. this.loadingContext = {
  3101. requests: [],
  3102. nextRequestId: 0
  3103. };
  3104. }
  3105. FontLoader.prototype = {
  3106. insertRule: function fontLoaderInsertRule(rule) {
  3107. var styleElement = this.styleElement;
  3108. if (!styleElement) {
  3109. styleElement = this.styleElement = document.createElement('style');
  3110. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  3111. document.documentElement.getElementsByTagName('head')[0].appendChild(
  3112. styleElement);
  3113. }
  3114. var styleSheet = styleElement.sheet;
  3115. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  3116. },
  3117. clear: function fontLoaderClear() {
  3118. var styleElement = this.styleElement;
  3119. if (styleElement) {
  3120. styleElement.parentNode.removeChild(styleElement);
  3121. styleElement = this.styleElement = null;
  3122. }
  3123. this.nativeFontFaces.forEach(function(nativeFontFace) {
  3124. document.fonts.delete(nativeFontFace);
  3125. });
  3126. this.nativeFontFaces.length = 0;
  3127. },
  3128. get loadTestFont() {
  3129. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  3130. // height.
  3131. return shadow(this, 'loadTestFont', atob(
  3132. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  3133. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  3134. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  3135. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  3136. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  3137. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  3138. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  3139. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  3140. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  3141. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  3142. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  3143. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  3144. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  3145. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  3146. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  3147. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  3148. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  3149. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  3150. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  3151. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  3152. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  3153. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  3154. ));
  3155. },
  3156. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  3157. this.nativeFontFaces.push(nativeFontFace);
  3158. document.fonts.add(nativeFontFace);
  3159. },
  3160. bind: function fontLoaderBind(fonts, callback) {
  3161. assert(!isWorker, 'bind() shall be called from main thread');
  3162. var rules = [];
  3163. var fontsToLoad = [];
  3164. var fontLoadPromises = [];
  3165. var getNativeFontPromise = function(nativeFontFace) {
  3166. // Return a promise that is always fulfilled, even when the font fails to
  3167. // load.
  3168. return nativeFontFace.loaded.catch(function(e) {
  3169. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  3170. });
  3171. };
  3172. for (var i = 0, ii = fonts.length; i < ii; i++) {
  3173. var font = fonts[i];
  3174. // Add the font to the DOM only once or skip if the font
  3175. // is already loaded.
  3176. if (font.attached || font.loading === false) {
  3177. continue;
  3178. }
  3179. font.attached = true;
  3180. if (FontLoader.isFontLoadingAPISupported) {
  3181. var nativeFontFace = font.createNativeFontFace();
  3182. if (nativeFontFace) {
  3183. this.addNativeFontFace(nativeFontFace);
  3184. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  3185. }
  3186. } else {
  3187. var rule = font.createFontFaceRule();
  3188. if (rule) {
  3189. this.insertRule(rule);
  3190. rules.push(rule);
  3191. fontsToLoad.push(font);
  3192. }
  3193. }
  3194. }
  3195. var request = this.queueLoadingCallback(callback);
  3196. if (FontLoader.isFontLoadingAPISupported) {
  3197. Promise.all(fontLoadPromises).then(function() {
  3198. request.complete();
  3199. });
  3200. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  3201. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  3202. } else {
  3203. request.complete();
  3204. }
  3205. },
  3206. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  3207. function LoadLoader_completeRequest() {
  3208. assert(!request.end, 'completeRequest() cannot be called twice');
  3209. request.end = Date.now();
  3210. // sending all completed requests in order how they were queued
  3211. while (context.requests.length > 0 && context.requests[0].end) {
  3212. var otherRequest = context.requests.shift();
  3213. setTimeout(otherRequest.callback, 0);
  3214. }
  3215. }
  3216. var context = this.loadingContext;
  3217. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  3218. var request = {
  3219. id: requestId,
  3220. complete: LoadLoader_completeRequest,
  3221. callback: callback,
  3222. started: Date.now()
  3223. };
  3224. context.requests.push(request);
  3225. return request;
  3226. },
  3227. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  3228. fonts,
  3229. request) {
  3230. /** Hack begin */
  3231. // There's currently no event when a font has finished downloading so the
  3232. // following code is a dirty hack to 'guess' when a font is
  3233. // ready. It's assumed fonts are loaded in order, so add a known test
  3234. // font after the desired fonts and then test for the loading of that
  3235. // test font.
  3236. function int32(data, offset) {
  3237. return (data.charCodeAt(offset) << 24) |
  3238. (data.charCodeAt(offset + 1) << 16) |
  3239. (data.charCodeAt(offset + 2) << 8) |
  3240. (data.charCodeAt(offset + 3) & 0xff);
  3241. }
  3242. function spliceString(s, offset, remove, insert) {
  3243. var chunk1 = s.substr(0, offset);
  3244. var chunk2 = s.substr(offset + remove);
  3245. return chunk1 + insert + chunk2;
  3246. }
  3247. var i, ii;
  3248. var canvas = document.createElement('canvas');
  3249. canvas.width = 1;
  3250. canvas.height = 1;
  3251. var ctx = canvas.getContext('2d');
  3252. var called = 0;
  3253. function isFontReady(name, callback) {
  3254. called++;
  3255. // With setTimeout clamping this gives the font ~100ms to load.
  3256. if(called > 30) {
  3257. warn('Load test font never loaded.');
  3258. callback();
  3259. return;
  3260. }
  3261. ctx.font = '30px ' + name;
  3262. ctx.fillText('.', 0, 20);
  3263. var imageData = ctx.getImageData(0, 0, 1, 1);
  3264. if (imageData.data[3] > 0) {
  3265. callback();
  3266. return;
  3267. }
  3268. setTimeout(isFontReady.bind(null, name, callback));
  3269. }
  3270. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  3271. // Chromium seems to cache fonts based on a hash of the actual font data,
  3272. // so the font must be modified for each load test else it will appear to
  3273. // be loaded already.
  3274. // TODO: This could maybe be made faster by avoiding the btoa of the full
  3275. // font by splitting it in chunks before hand and padding the font id.
  3276. var data = this.loadTestFont;
  3277. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  3278. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  3279. loadTestFontId);
  3280. // CFF checksum is important for IE, adjusting it
  3281. var CFF_CHECKSUM_OFFSET = 16;
  3282. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  3283. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  3284. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  3285. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  3286. }
  3287. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  3288. checksum = (checksum - XXXX_VALUE +
  3289. int32(loadTestFontId + 'XXX', i)) | 0;
  3290. }
  3291. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  3292. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  3293. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  3294. url + '}';
  3295. this.insertRule(rule);
  3296. var names = [];
  3297. for (i = 0, ii = fonts.length; i < ii; i++) {
  3298. names.push(fonts[i].loadedName);
  3299. }
  3300. names.push(loadTestFontId);
  3301. var div = document.createElement('div');
  3302. div.setAttribute('style',
  3303. 'visibility: hidden;' +
  3304. 'width: 10px; height: 10px;' +
  3305. 'position: absolute; top: 0px; left: 0px;');
  3306. for (i = 0, ii = names.length; i < ii; ++i) {
  3307. var span = document.createElement('span');
  3308. span.textContent = 'Hi';
  3309. span.style.fontFamily = names[i];
  3310. div.appendChild(span);
  3311. }
  3312. document.body.appendChild(div);
  3313. isFontReady(loadTestFontId, function() {
  3314. document.body.removeChild(div);
  3315. request.complete();
  3316. });
  3317. /** Hack end */
  3318. }
  3319. };
  3320. FontLoader.isFontLoadingAPISupported = (!isWorker &&
  3321. typeof document !== 'undefined' && !!document.fonts);
  3322. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  3323. get: function () {
  3324. var supported = false;
  3325. // User agent string sniffing is bad, but there is no reliable way to tell
  3326. // if font is fully loaded and ready to be used with canvas.
  3327. var userAgent = window.navigator.userAgent;
  3328. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  3329. if (m && m[1] >= 14) {
  3330. supported = true;
  3331. }
  3332. // TODO other browsers
  3333. if (userAgent === 'node') {
  3334. supported = true;
  3335. }
  3336. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  3337. },
  3338. enumerable: true,
  3339. configurable: true
  3340. });
  3341. var FontFaceObject = (function FontFaceObjectClosure() {
  3342. function FontFaceObject(translatedData) {
  3343. this.compiledGlyphs = Object.create(null);
  3344. // importing translated data
  3345. for (var i in translatedData) {
  3346. this[i] = translatedData[i];
  3347. }
  3348. }
  3349. Object.defineProperty(FontFaceObject, 'isEvalSupported', {
  3350. get: function () {
  3351. var evalSupport = false;
  3352. if (PDFJS.isEvalSupported) {
  3353. try {
  3354. /* jshint evil: true */
  3355. new Function('');
  3356. evalSupport = true;
  3357. } catch (e) {}
  3358. }
  3359. return shadow(this, 'isEvalSupported', evalSupport);
  3360. },
  3361. enumerable: true,
  3362. configurable: true
  3363. });
  3364. FontFaceObject.prototype = {
  3365. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  3366. if (!this.data) {
  3367. return null;
  3368. }
  3369. if (PDFJS.disableFontFace) {
  3370. this.disableFontFace = true;
  3371. return null;
  3372. }
  3373. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  3374. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  3375. globalScope['FontInspector'].enabled) {
  3376. globalScope['FontInspector'].fontAdded(this);
  3377. }
  3378. return nativeFontFace;
  3379. },
  3380. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  3381. if (!this.data) {
  3382. return null;
  3383. }
  3384. if (PDFJS.disableFontFace) {
  3385. this.disableFontFace = true;
  3386. return null;
  3387. }
  3388. var data = bytesToString(new Uint8Array(this.data));
  3389. var fontName = this.loadedName;
  3390. // Add the font-face rule to the document
  3391. var url = ('url(data:' + this.mimetype + ';base64,' +
  3392. window.btoa(data) + ');');
  3393. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  3394. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  3395. globalScope['FontInspector'].enabled) {
  3396. globalScope['FontInspector'].fontAdded(this, url);
  3397. }
  3398. return rule;
  3399. },
  3400. getPathGenerator:
  3401. function FontFaceObject_getPathGenerator(objs, character) {
  3402. if (!(character in this.compiledGlyphs)) {
  3403. var cmds = objs.get(this.loadedName + '_path_' + character);
  3404. var current, i, len;
  3405. // If we can, compile cmds into JS for MAXIMUM SPEED
  3406. if (FontFaceObject.isEvalSupported) {
  3407. var args, js = '';
  3408. for (i = 0, len = cmds.length; i < len; i++) {
  3409. current = cmds[i];
  3410. if (current.args !== undefined) {
  3411. args = current.args.join(',');
  3412. } else {
  3413. args = '';
  3414. }
  3415. js += 'c.' + current.cmd + '(' + args + ');\n';
  3416. }
  3417. /* jshint -W054 */
  3418. this.compiledGlyphs[character] = new Function('c', 'size', js);
  3419. } else {
  3420. // But fall back on using Function.prototype.apply() if we're
  3421. // blocked from using eval() for whatever reason (like CSP policies)
  3422. this.compiledGlyphs[character] = function(c, size) {
  3423. for (i = 0, len = cmds.length; i < len; i++) {
  3424. current = cmds[i];
  3425. if (current.cmd === 'scale') {
  3426. current.args = [size, -size];
  3427. }
  3428. c[current.cmd].apply(c, current.args);
  3429. }
  3430. };
  3431. }
  3432. }
  3433. return this.compiledGlyphs[character];
  3434. }
  3435. };
  3436. return FontFaceObject;
  3437. })();
  3438. exports.FontFaceObject = FontFaceObject;
  3439. exports.FontLoader = FontLoader;
  3440. }));
  3441. (function (root, factory) {
  3442. {
  3443. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  3444. }
  3445. }(this, function (exports, sharedUtil) {
  3446. var error = sharedUtil.error;
  3447. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  3448. function fixMetadata(meta) {
  3449. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  3450. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  3451. function(code, d1, d2, d3) {
  3452. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  3453. });
  3454. var chars = '';
  3455. for (var i = 0; i < bytes.length; i += 2) {
  3456. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  3457. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  3458. code !== 38 && false ? String.fromCharCode(code) :
  3459. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  3460. }
  3461. return '>' + chars;
  3462. });
  3463. }
  3464. function Metadata(meta) {
  3465. if (typeof meta === 'string') {
  3466. // Ghostscript produces invalid metadata
  3467. meta = fixMetadata(meta);
  3468. var parser = new DOMParser();
  3469. meta = parser.parseFromString(meta, 'application/xml');
  3470. } else if (!(meta instanceof Document)) {
  3471. error('Metadata: Invalid metadata object');
  3472. }
  3473. this.metaDocument = meta;
  3474. this.metadata = Object.create(null);
  3475. this.parse();
  3476. }
  3477. Metadata.prototype = {
  3478. parse: function Metadata_parse() {
  3479. var doc = this.metaDocument;
  3480. var rdf = doc.documentElement;
  3481. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  3482. rdf = rdf.firstChild;
  3483. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3484. rdf = rdf.nextSibling;
  3485. }
  3486. }
  3487. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  3488. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3489. return;
  3490. }
  3491. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3492. for (i = 0, length = children.length; i < length; i++) {
  3493. desc = children[i];
  3494. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3495. continue;
  3496. }
  3497. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3498. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3499. entry = desc.childNodes[ii];
  3500. name = entry.nodeName.toLowerCase();
  3501. this.metadata[name] = entry.textContent.trim();
  3502. }
  3503. }
  3504. }
  3505. },
  3506. get: function Metadata_get(name) {
  3507. return this.metadata[name] || null;
  3508. },
  3509. has: function Metadata_has(name) {
  3510. return typeof this.metadata[name] !== 'undefined';
  3511. }
  3512. };
  3513. return Metadata;
  3514. })();
  3515. exports.Metadata = Metadata;
  3516. }));
  3517. (function (root, factory) {
  3518. {
  3519. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  3520. }
  3521. }(this, function (exports, sharedUtil) {
  3522. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  3523. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  3524. var ImageKind = sharedUtil.ImageKind;
  3525. var OPS = sharedUtil.OPS;
  3526. var Util = sharedUtil.Util;
  3527. var isNum = sharedUtil.isNum;
  3528. var isArray = sharedUtil.isArray;
  3529. var warn = sharedUtil.warn;
  3530. var SVG_DEFAULTS = {
  3531. fontStyle: 'normal',
  3532. fontWeight: 'normal',
  3533. fillColor: '#000000'
  3534. };
  3535. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  3536. var PNG_HEADER =
  3537. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  3538. var CHUNK_WRAPPER_SIZE = 12;
  3539. var crcTable = new Int32Array(256);
  3540. for (var i = 0; i < 256; i++) {
  3541. var c = i;
  3542. for (var h = 0; h < 8; h++) {
  3543. if (c & 1) {
  3544. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  3545. } else {
  3546. c = (c >> 1) & 0x7fffffff;
  3547. }
  3548. }
  3549. crcTable[i] = c;
  3550. }
  3551. function crc32(data, start, end) {
  3552. var crc = -1;
  3553. for (var i = start; i < end; i++) {
  3554. var a = (crc ^ data[i]) & 0xff;
  3555. var b = crcTable[a];
  3556. crc = (crc >>> 8) ^ b;
  3557. }
  3558. return crc ^ -1;
  3559. }
  3560. function writePngChunk(type, body, data, offset) {
  3561. var p = offset;
  3562. var len = body.length;
  3563. data[p] = len >> 24 & 0xff;
  3564. data[p + 1] = len >> 16 & 0xff;
  3565. data[p + 2] = len >> 8 & 0xff;
  3566. data[p + 3] = len & 0xff;
  3567. p += 4;
  3568. data[p] = type.charCodeAt(0) & 0xff;
  3569. data[p + 1] = type.charCodeAt(1) & 0xff;
  3570. data[p + 2] = type.charCodeAt(2) & 0xff;
  3571. data[p + 3] = type.charCodeAt(3) & 0xff;
  3572. p += 4;
  3573. data.set(body, p);
  3574. p += body.length;
  3575. var crc = crc32(data, offset + 4, p);
  3576. data[p] = crc >> 24 & 0xff;
  3577. data[p + 1] = crc >> 16 & 0xff;
  3578. data[p + 2] = crc >> 8 & 0xff;
  3579. data[p + 3] = crc & 0xff;
  3580. }
  3581. function adler32(data, start, end) {
  3582. var a = 1;
  3583. var b = 0;
  3584. for (var i = start; i < end; ++i) {
  3585. a = (a + (data[i] & 0xff)) % 65521;
  3586. b = (b + a) % 65521;
  3587. }
  3588. return (b << 16) | a;
  3589. }
  3590. function encode(imgData, kind) {
  3591. var width = imgData.width;
  3592. var height = imgData.height;
  3593. var bitDepth, colorType, lineSize;
  3594. var bytes = imgData.data;
  3595. switch (kind) {
  3596. case ImageKind.GRAYSCALE_1BPP:
  3597. colorType = 0;
  3598. bitDepth = 1;
  3599. lineSize = (width + 7) >> 3;
  3600. break;
  3601. case ImageKind.RGB_24BPP:
  3602. colorType = 2;
  3603. bitDepth = 8;
  3604. lineSize = width * 3;
  3605. break;
  3606. case ImageKind.RGBA_32BPP:
  3607. colorType = 6;
  3608. bitDepth = 8;
  3609. lineSize = width * 4;
  3610. break;
  3611. default:
  3612. throw new Error('invalid format');
  3613. }
  3614. // prefix every row with predictor 0
  3615. var literals = new Uint8Array((1 + lineSize) * height);
  3616. var offsetLiterals = 0, offsetBytes = 0;
  3617. var y, i;
  3618. for (y = 0; y < height; ++y) {
  3619. literals[offsetLiterals++] = 0; // no prediction
  3620. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  3621. offsetLiterals);
  3622. offsetBytes += lineSize;
  3623. offsetLiterals += lineSize;
  3624. }
  3625. if (kind === ImageKind.GRAYSCALE_1BPP) {
  3626. // inverting for B/W
  3627. offsetLiterals = 0;
  3628. for (y = 0; y < height; y++) {
  3629. offsetLiterals++; // skipping predictor
  3630. for (i = 0; i < lineSize; i++) {
  3631. literals[offsetLiterals++] ^= 0xFF;
  3632. }
  3633. }
  3634. }
  3635. var ihdr = new Uint8Array([
  3636. width >> 24 & 0xff,
  3637. width >> 16 & 0xff,
  3638. width >> 8 & 0xff,
  3639. width & 0xff,
  3640. height >> 24 & 0xff,
  3641. height >> 16 & 0xff,
  3642. height >> 8 & 0xff,
  3643. height & 0xff,
  3644. bitDepth, // bit depth
  3645. colorType, // color type
  3646. 0x00, // compression method
  3647. 0x00, // filter method
  3648. 0x00 // interlace method
  3649. ]);
  3650. var len = literals.length;
  3651. var maxBlockLength = 0xFFFF;
  3652. var deflateBlocks = Math.ceil(len / maxBlockLength);
  3653. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  3654. var pi = 0;
  3655. idat[pi++] = 0x78; // compression method and flags
  3656. idat[pi++] = 0x9c; // flags
  3657. var pos = 0;
  3658. while (len > maxBlockLength) {
  3659. // writing non-final DEFLATE blocks type 0 and length of 65535
  3660. idat[pi++] = 0x00;
  3661. idat[pi++] = 0xff;
  3662. idat[pi++] = 0xff;
  3663. idat[pi++] = 0x00;
  3664. idat[pi++] = 0x00;
  3665. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  3666. pi += maxBlockLength;
  3667. pos += maxBlockLength;
  3668. len -= maxBlockLength;
  3669. }
  3670. // writing non-final DEFLATE blocks type 0
  3671. idat[pi++] = 0x01;
  3672. idat[pi++] = len & 0xff;
  3673. idat[pi++] = len >> 8 & 0xff;
  3674. idat[pi++] = (~len & 0xffff) & 0xff;
  3675. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3676. idat.set(literals.subarray(pos), pi);
  3677. pi += literals.length - pos;
  3678. var adler = adler32(literals, 0, literals.length); // checksum
  3679. idat[pi++] = adler >> 24 & 0xff;
  3680. idat[pi++] = adler >> 16 & 0xff;
  3681. idat[pi++] = adler >> 8 & 0xff;
  3682. idat[pi++] = adler & 0xff;
  3683. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3684. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  3685. ihdr.length + idat.length;
  3686. var data = new Uint8Array(pngLength);
  3687. var offset = 0;
  3688. data.set(PNG_HEADER, offset);
  3689. offset += PNG_HEADER.length;
  3690. writePngChunk('IHDR', ihdr, data, offset);
  3691. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3692. writePngChunk('IDATA', idat, data, offset);
  3693. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3694. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3695. return PDFJS.createObjectURL(data, 'image/png');
  3696. }
  3697. return function convertImgDataToPng(imgData) {
  3698. var kind = (imgData.kind === undefined ?
  3699. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  3700. return encode(imgData, kind);
  3701. };
  3702. })();
  3703. var SVGExtraState = (function SVGExtraStateClosure() {
  3704. function SVGExtraState() {
  3705. this.fontSizeScale = 1;
  3706. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3707. this.fontSize = 0;
  3708. this.textMatrix = IDENTITY_MATRIX;
  3709. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3710. this.leading = 0;
  3711. // Current point (in user coordinates)
  3712. this.x = 0;
  3713. this.y = 0;
  3714. // Start of text line (in text coordinates)
  3715. this.lineX = 0;
  3716. this.lineY = 0;
  3717. // Character and word spacing
  3718. this.charSpacing = 0;
  3719. this.wordSpacing = 0;
  3720. this.textHScale = 1;
  3721. this.textRise = 0;
  3722. // Default foreground and background colors
  3723. this.fillColor = SVG_DEFAULTS.fillColor;
  3724. this.strokeColor = '#000000';
  3725. this.fillAlpha = 1;
  3726. this.strokeAlpha = 1;
  3727. this.lineWidth = 1;
  3728. this.lineJoin = '';
  3729. this.lineCap = '';
  3730. this.miterLimit = 0;
  3731. this.dashArray = [];
  3732. this.dashPhase = 0;
  3733. this.dependencies = [];
  3734. // Clipping
  3735. this.clipId = '';
  3736. this.pendingClip = false;
  3737. this.maskId = '';
  3738. }
  3739. SVGExtraState.prototype = {
  3740. clone: function SVGExtraState_clone() {
  3741. return Object.create(this);
  3742. },
  3743. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3744. this.x = x;
  3745. this.y = y;
  3746. }
  3747. };
  3748. return SVGExtraState;
  3749. })();
  3750. var SVGGraphics = (function SVGGraphicsClosure() {
  3751. function createScratchSVG(width, height) {
  3752. var NS = 'http://www.w3.org/2000/svg';
  3753. var svg = document.createElementNS(NS, 'svg:svg');
  3754. svg.setAttributeNS(null, 'version', '1.1');
  3755. svg.setAttributeNS(null, 'width', width + 'px');
  3756. svg.setAttributeNS(null, 'height', height + 'px');
  3757. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3758. return svg;
  3759. }
  3760. function opListToTree(opList) {
  3761. var opTree = [];
  3762. var tmp = [];
  3763. var opListLen = opList.length;
  3764. for (var x = 0; x < opListLen; x++) {
  3765. if (opList[x].fn === 'save') {
  3766. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3767. tmp.push(opTree);
  3768. opTree = opTree[opTree.length - 1].items;
  3769. continue;
  3770. }
  3771. if(opList[x].fn === 'restore') {
  3772. opTree = tmp.pop();
  3773. } else {
  3774. opTree.push(opList[x]);
  3775. }
  3776. }
  3777. return opTree;
  3778. }
  3779. /**
  3780. * Formats float number.
  3781. * @param value {number} number to format.
  3782. * @returns {string}
  3783. */
  3784. function pf(value) {
  3785. if (value === (value | 0)) { // integer number
  3786. return value.toString();
  3787. }
  3788. var s = value.toFixed(10);
  3789. var i = s.length - 1;
  3790. if (s[i] !== '0') {
  3791. return s;
  3792. }
  3793. // removing trailing zeros
  3794. do {
  3795. i--;
  3796. } while (s[i] === '0');
  3797. return s.substr(0, s[i] === '.' ? i : i + 1);
  3798. }
  3799. /**
  3800. * Formats transform matrix. The standard rotation, scale and translate
  3801. * matrices are replaced by their shorter forms, and for identity matrix
  3802. * returns empty string to save the memory.
  3803. * @param m {Array} matrix to format.
  3804. * @returns {string}
  3805. */
  3806. function pm(m) {
  3807. if (m[4] === 0 && m[5] === 0) {
  3808. if (m[1] === 0 && m[2] === 0) {
  3809. if (m[0] === 1 && m[3] === 1) {
  3810. return '';
  3811. }
  3812. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3813. }
  3814. if (m[0] === m[3] && m[1] === -m[2]) {
  3815. var a = Math.acos(m[0]) * 180 / Math.PI;
  3816. return 'rotate(' + pf(a) + ')';
  3817. }
  3818. } else {
  3819. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3820. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3821. }
  3822. }
  3823. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3824. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3825. }
  3826. function SVGGraphics(commonObjs, objs) {
  3827. this.current = new SVGExtraState();
  3828. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3829. this.transformStack = [];
  3830. this.extraStack = [];
  3831. this.commonObjs = commonObjs;
  3832. this.objs = objs;
  3833. this.pendingEOFill = false;
  3834. this.embedFonts = false;
  3835. this.embeddedFonts = Object.create(null);
  3836. this.cssStyle = null;
  3837. }
  3838. var NS = 'http://www.w3.org/2000/svg';
  3839. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3840. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3841. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3842. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3843. var clipCount = 0;
  3844. var maskCount = 0;
  3845. SVGGraphics.prototype = {
  3846. save: function SVGGraphics_save() {
  3847. this.transformStack.push(this.transformMatrix);
  3848. var old = this.current;
  3849. this.extraStack.push(old);
  3850. this.current = old.clone();
  3851. },
  3852. restore: function SVGGraphics_restore() {
  3853. this.transformMatrix = this.transformStack.pop();
  3854. this.current = this.extraStack.pop();
  3855. this.tgrp = document.createElementNS(NS, 'svg:g');
  3856. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3857. this.pgrp.appendChild(this.tgrp);
  3858. },
  3859. group: function SVGGraphics_group(items) {
  3860. this.save();
  3861. this.executeOpTree(items);
  3862. this.restore();
  3863. },
  3864. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3865. var fnArray = operatorList.fnArray;
  3866. var fnArrayLen = fnArray.length;
  3867. var argsArray = operatorList.argsArray;
  3868. var self = this;
  3869. for (var i = 0; i < fnArrayLen; i++) {
  3870. if (OPS.dependency === fnArray[i]) {
  3871. var deps = argsArray[i];
  3872. for (var n = 0, nn = deps.length; n < nn; n++) {
  3873. var obj = deps[n];
  3874. var common = obj.substring(0, 2) === 'g_';
  3875. var promise;
  3876. if (common) {
  3877. promise = new Promise(function(resolve) {
  3878. self.commonObjs.get(obj, resolve);
  3879. });
  3880. } else {
  3881. promise = new Promise(function(resolve) {
  3882. self.objs.get(obj, resolve);
  3883. });
  3884. }
  3885. this.current.dependencies.push(promise);
  3886. }
  3887. }
  3888. }
  3889. return Promise.all(this.current.dependencies);
  3890. },
  3891. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3892. var transformMatrix = [a, b, c, d, e, f];
  3893. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  3894. transformMatrix);
  3895. this.tgrp = document.createElementNS(NS, 'svg:g');
  3896. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3897. },
  3898. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3899. this.svg = createScratchSVG(viewport.width, viewport.height);
  3900. this.viewport = viewport;
  3901. return this.loadDependencies(operatorList).then(function () {
  3902. this.transformMatrix = IDENTITY_MATRIX;
  3903. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3904. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3905. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3906. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3907. this.defs = document.createElementNS(NS, 'svg:defs');
  3908. this.pgrp.appendChild(this.defs);
  3909. this.pgrp.appendChild(this.tgrp);
  3910. this.svg.appendChild(this.pgrp);
  3911. var opTree = this.convertOpList(operatorList);
  3912. this.executeOpTree(opTree);
  3913. return this.svg;
  3914. }.bind(this));
  3915. },
  3916. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3917. var argsArray = operatorList.argsArray;
  3918. var fnArray = operatorList.fnArray;
  3919. var fnArrayLen = fnArray.length;
  3920. var REVOPS = [];
  3921. var opList = [];
  3922. for (var op in OPS) {
  3923. REVOPS[OPS[op]] = op;
  3924. }
  3925. for (var x = 0; x < fnArrayLen; x++) {
  3926. var fnId = fnArray[x];
  3927. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3928. }
  3929. return opListToTree(opList);
  3930. },
  3931. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3932. var opTreeLen = opTree.length;
  3933. for(var x = 0; x < opTreeLen; x++) {
  3934. var fn = opTree[x].fn;
  3935. var fnId = opTree[x].fnId;
  3936. var args = opTree[x].args;
  3937. switch (fnId | 0) {
  3938. case OPS.beginText:
  3939. this.beginText();
  3940. break;
  3941. case OPS.setLeading:
  3942. this.setLeading(args);
  3943. break;
  3944. case OPS.setLeadingMoveText:
  3945. this.setLeadingMoveText(args[0], args[1]);
  3946. break;
  3947. case OPS.setFont:
  3948. this.setFont(args);
  3949. break;
  3950. case OPS.showText:
  3951. this.showText(args[0]);
  3952. break;
  3953. case OPS.showSpacedText:
  3954. this.showText(args[0]);
  3955. break;
  3956. case OPS.endText:
  3957. this.endText();
  3958. break;
  3959. case OPS.moveText:
  3960. this.moveText(args[0], args[1]);
  3961. break;
  3962. case OPS.setCharSpacing:
  3963. this.setCharSpacing(args[0]);
  3964. break;
  3965. case OPS.setWordSpacing:
  3966. this.setWordSpacing(args[0]);
  3967. break;
  3968. case OPS.setHScale:
  3969. this.setHScale(args[0]);
  3970. break;
  3971. case OPS.setTextMatrix:
  3972. this.setTextMatrix(args[0], args[1], args[2],
  3973. args[3], args[4], args[5]);
  3974. break;
  3975. case OPS.setLineWidth:
  3976. this.setLineWidth(args[0]);
  3977. break;
  3978. case OPS.setLineJoin:
  3979. this.setLineJoin(args[0]);
  3980. break;
  3981. case OPS.setLineCap:
  3982. this.setLineCap(args[0]);
  3983. break;
  3984. case OPS.setMiterLimit:
  3985. this.setMiterLimit(args[0]);
  3986. break;
  3987. case OPS.setFillRGBColor:
  3988. this.setFillRGBColor(args[0], args[1], args[2]);
  3989. break;
  3990. case OPS.setStrokeRGBColor:
  3991. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3992. break;
  3993. case OPS.setDash:
  3994. this.setDash(args[0], args[1]);
  3995. break;
  3996. case OPS.setGState:
  3997. this.setGState(args[0]);
  3998. break;
  3999. case OPS.fill:
  4000. this.fill();
  4001. break;
  4002. case OPS.eoFill:
  4003. this.eoFill();
  4004. break;
  4005. case OPS.stroke:
  4006. this.stroke();
  4007. break;
  4008. case OPS.fillStroke:
  4009. this.fillStroke();
  4010. break;
  4011. case OPS.eoFillStroke:
  4012. this.eoFillStroke();
  4013. break;
  4014. case OPS.clip:
  4015. this.clip('nonzero');
  4016. break;
  4017. case OPS.eoClip:
  4018. this.clip('evenodd');
  4019. break;
  4020. case OPS.paintSolidColorImageMask:
  4021. this.paintSolidColorImageMask();
  4022. break;
  4023. case OPS.paintJpegXObject:
  4024. this.paintJpegXObject(args[0], args[1], args[2]);
  4025. break;
  4026. case OPS.paintImageXObject:
  4027. this.paintImageXObject(args[0]);
  4028. break;
  4029. case OPS.paintInlineImageXObject:
  4030. this.paintInlineImageXObject(args[0]);
  4031. break;
  4032. case OPS.paintImageMaskXObject:
  4033. this.paintImageMaskXObject(args[0]);
  4034. break;
  4035. case OPS.paintFormXObjectBegin:
  4036. this.paintFormXObjectBegin(args[0], args[1]);
  4037. break;
  4038. case OPS.paintFormXObjectEnd:
  4039. this.paintFormXObjectEnd();
  4040. break;
  4041. case OPS.closePath:
  4042. this.closePath();
  4043. break;
  4044. case OPS.closeStroke:
  4045. this.closeStroke();
  4046. break;
  4047. case OPS.closeFillStroke:
  4048. this.closeFillStroke();
  4049. break;
  4050. case OPS.nextLine:
  4051. this.nextLine();
  4052. break;
  4053. case OPS.transform:
  4054. this.transform(args[0], args[1], args[2], args[3],
  4055. args[4], args[5]);
  4056. break;
  4057. case OPS.constructPath:
  4058. this.constructPath(args[0], args[1]);
  4059. break;
  4060. case OPS.endPath:
  4061. this.endPath();
  4062. break;
  4063. case 92:
  4064. this.group(opTree[x].items);
  4065. break;
  4066. default:
  4067. warn('Unimplemented method '+ fn);
  4068. break;
  4069. }
  4070. }
  4071. },
  4072. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  4073. this.current.wordSpacing = wordSpacing;
  4074. },
  4075. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  4076. this.current.charSpacing = charSpacing;
  4077. },
  4078. nextLine: function SVGGraphics_nextLine() {
  4079. this.moveText(0, this.current.leading);
  4080. },
  4081. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  4082. var current = this.current;
  4083. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  4084. this.current.x = this.current.lineX = 0;
  4085. this.current.y = this.current.lineY = 0;
  4086. current.xcoords = [];
  4087. current.tspan = document.createElementNS(NS, 'svg:tspan');
  4088. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  4089. current.tspan.setAttributeNS(null, 'font-size',
  4090. pf(current.fontSize) + 'px');
  4091. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  4092. current.txtElement = document.createElementNS(NS, 'svg:text');
  4093. current.txtElement.appendChild(current.tspan);
  4094. },
  4095. beginText: function SVGGraphics_beginText() {
  4096. this.current.x = this.current.lineX = 0;
  4097. this.current.y = this.current.lineY = 0;
  4098. this.current.textMatrix = IDENTITY_MATRIX;
  4099. this.current.lineMatrix = IDENTITY_MATRIX;
  4100. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  4101. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  4102. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  4103. this.current.xcoords = [];
  4104. },
  4105. moveText: function SVGGraphics_moveText(x, y) {
  4106. var current = this.current;
  4107. this.current.x = this.current.lineX += x;
  4108. this.current.y = this.current.lineY += y;
  4109. current.xcoords = [];
  4110. current.tspan = document.createElementNS(NS, 'svg:tspan');
  4111. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  4112. current.tspan.setAttributeNS(null, 'font-size',
  4113. pf(current.fontSize) + 'px');
  4114. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  4115. },
  4116. showText: function SVGGraphics_showText(glyphs) {
  4117. var current = this.current;
  4118. var font = current.font;
  4119. var fontSize = current.fontSize;
  4120. if (fontSize === 0) {
  4121. return;
  4122. }
  4123. var charSpacing = current.charSpacing;
  4124. var wordSpacing = current.wordSpacing;
  4125. var fontDirection = current.fontDirection;
  4126. var textHScale = current.textHScale * fontDirection;
  4127. var glyphsLength = glyphs.length;
  4128. var vertical = font.vertical;
  4129. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4130. var x = 0, i;
  4131. for (i = 0; i < glyphsLength; ++i) {
  4132. var glyph = glyphs[i];
  4133. if (glyph === null) {
  4134. // word break
  4135. x += fontDirection * wordSpacing;
  4136. continue;
  4137. } else if (isNum(glyph)) {
  4138. x += -glyph * fontSize * 0.001;
  4139. continue;
  4140. }
  4141. current.xcoords.push(current.x + x * textHScale);
  4142. var width = glyph.width;
  4143. var character = glyph.fontChar;
  4144. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4145. x += charWidth;
  4146. current.tspan.textContent += character;
  4147. }
  4148. if (vertical) {
  4149. current.y -= x * textHScale;
  4150. } else {
  4151. current.x += x * textHScale;
  4152. }
  4153. current.tspan.setAttributeNS(null, 'x',
  4154. current.xcoords.map(pf).join(' '));
  4155. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  4156. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  4157. current.tspan.setAttributeNS(null, 'font-size',
  4158. pf(current.fontSize) + 'px');
  4159. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  4160. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  4161. }
  4162. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  4163. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  4164. }
  4165. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  4166. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  4167. }
  4168. current.txtElement.setAttributeNS(null, 'transform',
  4169. pm(current.textMatrix) +
  4170. ' scale(1, -1)' );
  4171. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  4172. current.txtElement.appendChild(current.tspan);
  4173. current.txtgrp.appendChild(current.txtElement);
  4174. this.tgrp.appendChild(current.txtElement);
  4175. },
  4176. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  4177. this.setLeading(-y);
  4178. this.moveText(x, y);
  4179. },
  4180. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  4181. if (!this.cssStyle) {
  4182. this.cssStyle = document.createElementNS(NS, 'svg:style');
  4183. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  4184. this.defs.appendChild(this.cssStyle);
  4185. }
  4186. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  4187. this.cssStyle.textContent +=
  4188. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  4189. ' src: url(' + url + '); }\n';
  4190. },
  4191. setFont: function SVGGraphics_setFont(details) {
  4192. var current = this.current;
  4193. var fontObj = this.commonObjs.get(details[0]);
  4194. var size = details[1];
  4195. this.current.font = fontObj;
  4196. if (this.embedFonts && fontObj.data &&
  4197. !this.embeddedFonts[fontObj.loadedName]) {
  4198. this.addFontStyle(fontObj);
  4199. this.embeddedFonts[fontObj.loadedName] = fontObj;
  4200. }
  4201. current.fontMatrix = (fontObj.fontMatrix ?
  4202. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4203. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  4204. (fontObj.bold ? 'bold' : 'normal');
  4205. var italic = fontObj.italic ? 'italic' : 'normal';
  4206. if (size < 0) {
  4207. size = -size;
  4208. current.fontDirection = -1;
  4209. } else {
  4210. current.fontDirection = 1;
  4211. }
  4212. current.fontSize = size;
  4213. current.fontFamily = fontObj.loadedName;
  4214. current.fontWeight = bold;
  4215. current.fontStyle = italic;
  4216. current.tspan = document.createElementNS(NS, 'svg:tspan');
  4217. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  4218. current.xcoords = [];
  4219. },
  4220. endText: function SVGGraphics_endText() {
  4221. if (this.current.pendingClip) {
  4222. this.cgrp.appendChild(this.tgrp);
  4223. this.pgrp.appendChild(this.cgrp);
  4224. } else {
  4225. this.pgrp.appendChild(this.tgrp);
  4226. }
  4227. this.tgrp = document.createElementNS(NS, 'svg:g');
  4228. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4229. },
  4230. // Path properties
  4231. setLineWidth: function SVGGraphics_setLineWidth(width) {
  4232. this.current.lineWidth = width;
  4233. },
  4234. setLineCap: function SVGGraphics_setLineCap(style) {
  4235. this.current.lineCap = LINE_CAP_STYLES[style];
  4236. },
  4237. setLineJoin: function SVGGraphics_setLineJoin(style) {
  4238. this.current.lineJoin = LINE_JOIN_STYLES[style];
  4239. },
  4240. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  4241. this.current.miterLimit = limit;
  4242. },
  4243. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  4244. var color = Util.makeCssRgb(r, g, b);
  4245. this.current.strokeColor = color;
  4246. },
  4247. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  4248. var color = Util.makeCssRgb(r, g, b);
  4249. this.current.fillColor = color;
  4250. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  4251. this.current.xcoords = [];
  4252. },
  4253. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  4254. this.current.dashArray = dashArray;
  4255. this.current.dashPhase = dashPhase;
  4256. },
  4257. constructPath: function SVGGraphics_constructPath(ops, args) {
  4258. var current = this.current;
  4259. var x = current.x, y = current.y;
  4260. current.path = document.createElementNS(NS, 'svg:path');
  4261. var d = [];
  4262. var opLength = ops.length;
  4263. for (var i = 0, j = 0; i < opLength; i++) {
  4264. switch (ops[i] | 0) {
  4265. case OPS.rectangle:
  4266. x = args[j++];
  4267. y = args[j++];
  4268. var width = args[j++];
  4269. var height = args[j++];
  4270. var xw = x + width;
  4271. var yh = y + height;
  4272. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  4273. 'L', pf(x), pf(yh), 'Z');
  4274. break;
  4275. case OPS.moveTo:
  4276. x = args[j++];
  4277. y = args[j++];
  4278. d.push('M', pf(x), pf(y));
  4279. break;
  4280. case OPS.lineTo:
  4281. x = args[j++];
  4282. y = args[j++];
  4283. d.push('L', pf(x) , pf(y));
  4284. break;
  4285. case OPS.curveTo:
  4286. x = args[j + 4];
  4287. y = args[j + 5];
  4288. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  4289. pf(args[j + 3]), pf(x), pf(y));
  4290. j += 6;
  4291. break;
  4292. case OPS.curveTo2:
  4293. x = args[j + 2];
  4294. y = args[j + 3];
  4295. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  4296. pf(args[j + 2]), pf(args[j + 3]));
  4297. j += 4;
  4298. break;
  4299. case OPS.curveTo3:
  4300. x = args[j + 2];
  4301. y = args[j + 3];
  4302. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  4303. pf(x), pf(y));
  4304. j += 4;
  4305. break;
  4306. case OPS.closePath:
  4307. d.push('Z');
  4308. break;
  4309. }
  4310. }
  4311. current.path.setAttributeNS(null, 'd', d.join(' '));
  4312. current.path.setAttributeNS(null, 'stroke-miterlimit',
  4313. pf(current.miterLimit));
  4314. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  4315. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  4316. current.path.setAttributeNS(null, 'stroke-width',
  4317. pf(current.lineWidth) + 'px');
  4318. current.path.setAttributeNS(null, 'stroke-dasharray',
  4319. current.dashArray.map(pf).join(' '));
  4320. current.path.setAttributeNS(null, 'stroke-dashoffset',
  4321. pf(current.dashPhase) + 'px');
  4322. current.path.setAttributeNS(null, 'fill', 'none');
  4323. this.tgrp.appendChild(current.path);
  4324. if (current.pendingClip) {
  4325. this.cgrp.appendChild(this.tgrp);
  4326. this.pgrp.appendChild(this.cgrp);
  4327. } else {
  4328. this.pgrp.appendChild(this.tgrp);
  4329. }
  4330. // Saving a reference in current.element so that it can be addressed
  4331. // in 'fill' and 'stroke'
  4332. current.element = current.path;
  4333. current.setCurrentPoint(x, y);
  4334. },
  4335. endPath: function SVGGraphics_endPath() {
  4336. var current = this.current;
  4337. if (current.pendingClip) {
  4338. this.cgrp.appendChild(this.tgrp);
  4339. this.pgrp.appendChild(this.cgrp);
  4340. } else {
  4341. this.pgrp.appendChild(this.tgrp);
  4342. }
  4343. this.tgrp = document.createElementNS(NS, 'svg:g');
  4344. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4345. },
  4346. clip: function SVGGraphics_clip(type) {
  4347. var current = this.current;
  4348. // Add current path to clipping path
  4349. current.clipId = 'clippath' + clipCount;
  4350. clipCount++;
  4351. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  4352. this.clippath.setAttributeNS(null, 'id', current.clipId);
  4353. var clipElement = current.element.cloneNode();
  4354. if (type === 'evenodd') {
  4355. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  4356. } else {
  4357. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  4358. }
  4359. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4360. this.clippath.appendChild(clipElement);
  4361. this.defs.appendChild(this.clippath);
  4362. // Create a new group with that attribute
  4363. current.pendingClip = true;
  4364. this.cgrp = document.createElementNS(NS, 'svg:g');
  4365. this.cgrp.setAttributeNS(null, 'clip-path',
  4366. 'url(#' + current.clipId + ')');
  4367. this.pgrp.appendChild(this.cgrp);
  4368. },
  4369. closePath: function SVGGraphics_closePath() {
  4370. var current = this.current;
  4371. var d = current.path.getAttributeNS(null, 'd');
  4372. d += 'Z';
  4373. current.path.setAttributeNS(null, 'd', d);
  4374. },
  4375. setLeading: function SVGGraphics_setLeading(leading) {
  4376. this.current.leading = -leading;
  4377. },
  4378. setTextRise: function SVGGraphics_setTextRise(textRise) {
  4379. this.current.textRise = textRise;
  4380. },
  4381. setHScale: function SVGGraphics_setHScale(scale) {
  4382. this.current.textHScale = scale / 100;
  4383. },
  4384. setGState: function SVGGraphics_setGState(states) {
  4385. for (var i = 0, ii = states.length; i < ii; i++) {
  4386. var state = states[i];
  4387. var key = state[0];
  4388. var value = state[1];
  4389. switch (key) {
  4390. case 'LW':
  4391. this.setLineWidth(value);
  4392. break;
  4393. case 'LC':
  4394. this.setLineCap(value);
  4395. break;
  4396. case 'LJ':
  4397. this.setLineJoin(value);
  4398. break;
  4399. case 'ML':
  4400. this.setMiterLimit(value);
  4401. break;
  4402. case 'D':
  4403. this.setDash(value[0], value[1]);
  4404. break;
  4405. case 'RI':
  4406. break;
  4407. case 'FL':
  4408. break;
  4409. case 'Font':
  4410. this.setFont(value);
  4411. break;
  4412. case 'CA':
  4413. break;
  4414. case 'ca':
  4415. break;
  4416. case 'BM':
  4417. break;
  4418. case 'SMask':
  4419. break;
  4420. }
  4421. }
  4422. },
  4423. fill: function SVGGraphics_fill() {
  4424. var current = this.current;
  4425. current.element.setAttributeNS(null, 'fill', current.fillColor);
  4426. },
  4427. stroke: function SVGGraphics_stroke() {
  4428. var current = this.current;
  4429. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  4430. current.element.setAttributeNS(null, 'fill', 'none');
  4431. },
  4432. eoFill: function SVGGraphics_eoFill() {
  4433. var current = this.current;
  4434. current.element.setAttributeNS(null, 'fill', current.fillColor);
  4435. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  4436. },
  4437. fillStroke: function SVGGraphics_fillStroke() {
  4438. // Order is important since stroke wants fill to be none.
  4439. // First stroke, then if fill needed, it will be overwritten.
  4440. this.stroke();
  4441. this.fill();
  4442. },
  4443. eoFillStroke: function SVGGraphics_eoFillStroke() {
  4444. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  4445. this.fillStroke();
  4446. },
  4447. closeStroke: function SVGGraphics_closeStroke() {
  4448. this.closePath();
  4449. this.stroke();
  4450. },
  4451. closeFillStroke: function SVGGraphics_closeFillStroke() {
  4452. this.closePath();
  4453. this.fillStroke();
  4454. },
  4455. paintSolidColorImageMask:
  4456. function SVGGraphics_paintSolidColorImageMask() {
  4457. var current = this.current;
  4458. var rect = document.createElementNS(NS, 'svg:rect');
  4459. rect.setAttributeNS(null, 'x', '0');
  4460. rect.setAttributeNS(null, 'y', '0');
  4461. rect.setAttributeNS(null, 'width', '1px');
  4462. rect.setAttributeNS(null, 'height', '1px');
  4463. rect.setAttributeNS(null, 'fill', current.fillColor);
  4464. this.tgrp.appendChild(rect);
  4465. },
  4466. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  4467. var current = this.current;
  4468. var imgObj = this.objs.get(objId);
  4469. var imgEl = document.createElementNS(NS, 'svg:image');
  4470. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  4471. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  4472. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  4473. imgEl.setAttributeNS(null, 'x', '0');
  4474. imgEl.setAttributeNS(null, 'y', pf(-h));
  4475. imgEl.setAttributeNS(null, 'transform',
  4476. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  4477. this.tgrp.appendChild(imgEl);
  4478. if (current.pendingClip) {
  4479. this.cgrp.appendChild(this.tgrp);
  4480. this.pgrp.appendChild(this.cgrp);
  4481. } else {
  4482. this.pgrp.appendChild(this.tgrp);
  4483. }
  4484. },
  4485. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  4486. var imgData = this.objs.get(objId);
  4487. if (!imgData) {
  4488. warn('Dependent image isn\'t ready yet');
  4489. return;
  4490. }
  4491. this.paintInlineImageXObject(imgData);
  4492. },
  4493. paintInlineImageXObject:
  4494. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  4495. var current = this.current;
  4496. var width = imgData.width;
  4497. var height = imgData.height;
  4498. var imgSrc = convertImgDataToPng(imgData);
  4499. var cliprect = document.createElementNS(NS, 'svg:rect');
  4500. cliprect.setAttributeNS(null, 'x', '0');
  4501. cliprect.setAttributeNS(null, 'y', '0');
  4502. cliprect.setAttributeNS(null, 'width', pf(width));
  4503. cliprect.setAttributeNS(null, 'height', pf(height));
  4504. current.element = cliprect;
  4505. this.clip('nonzero');
  4506. var imgEl = document.createElementNS(NS, 'svg:image');
  4507. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4508. imgEl.setAttributeNS(null, 'x', '0');
  4509. imgEl.setAttributeNS(null, 'y', pf(-height));
  4510. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4511. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4512. imgEl.setAttributeNS(null, 'transform',
  4513. 'scale(' + pf(1 / width) + ' ' +
  4514. pf(-1 / height) + ')');
  4515. if (mask) {
  4516. mask.appendChild(imgEl);
  4517. } else {
  4518. this.tgrp.appendChild(imgEl);
  4519. }
  4520. if (current.pendingClip) {
  4521. this.cgrp.appendChild(this.tgrp);
  4522. this.pgrp.appendChild(this.cgrp);
  4523. } else {
  4524. this.pgrp.appendChild(this.tgrp);
  4525. }
  4526. },
  4527. paintImageMaskXObject:
  4528. function SVGGraphics_paintImageMaskXObject(imgData) {
  4529. var current = this.current;
  4530. var width = imgData.width;
  4531. var height = imgData.height;
  4532. var fillColor = current.fillColor;
  4533. current.maskId = 'mask' + maskCount++;
  4534. var mask = document.createElementNS(NS, 'svg:mask');
  4535. mask.setAttributeNS(null, 'id', current.maskId);
  4536. var rect = document.createElementNS(NS, 'svg:rect');
  4537. rect.setAttributeNS(null, 'x', '0');
  4538. rect.setAttributeNS(null, 'y', '0');
  4539. rect.setAttributeNS(null, 'width', pf(width));
  4540. rect.setAttributeNS(null, 'height', pf(height));
  4541. rect.setAttributeNS(null, 'fill', fillColor);
  4542. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  4543. this.defs.appendChild(mask);
  4544. this.tgrp.appendChild(rect);
  4545. this.paintInlineImageXObject(imgData, mask);
  4546. },
  4547. paintFormXObjectBegin:
  4548. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4549. this.save();
  4550. if (isArray(matrix) && matrix.length === 6) {
  4551. this.transform(matrix[0], matrix[1], matrix[2],
  4552. matrix[3], matrix[4], matrix[5]);
  4553. }
  4554. if (isArray(bbox) && bbox.length === 4) {
  4555. var width = bbox[2] - bbox[0];
  4556. var height = bbox[3] - bbox[1];
  4557. var cliprect = document.createElementNS(NS, 'svg:rect');
  4558. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4559. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4560. cliprect.setAttributeNS(null, 'width', pf(width));
  4561. cliprect.setAttributeNS(null, 'height', pf(height));
  4562. this.current.element = cliprect;
  4563. this.clip('nonzero');
  4564. this.endPath();
  4565. }
  4566. },
  4567. paintFormXObjectEnd:
  4568. function SVGGraphics_paintFormXObjectEnd() {
  4569. this.restore();
  4570. }
  4571. };
  4572. return SVGGraphics;
  4573. })();
  4574. PDFJS.SVGGraphics = SVGGraphics;
  4575. exports.SVGGraphics = SVGGraphics;
  4576. }));
  4577. (function (root, factory) {
  4578. {
  4579. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4580. root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal);
  4581. }
  4582. }(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) {
  4583. var Util = sharedUtil.Util;
  4584. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4585. var CustomStyle = displayDOMUtils.CustomStyle;
  4586. var PDFJS = sharedGlobal.PDFJS;
  4587. /**
  4588. * Text layer render parameters.
  4589. *
  4590. * @typedef {Object} TextLayerRenderParameters
  4591. * @property {TextContent} textContent - Text content to render (the object is
  4592. * returned by the page's getTextContent() method).
  4593. * @property {HTMLElement} container - HTML element that will contain text runs.
  4594. * @property {PDFJS.PageViewport} viewport - The target viewport to properly
  4595. * layout the text runs.
  4596. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4597. * the text items of the textContent input. This is output and shall be
  4598. * initially be set to empty array.
  4599. * @property {number} timeout - (optional) Delay in milliseconds before
  4600. * rendering of the text runs occurs.
  4601. */
  4602. var renderTextLayer = (function renderTextLayerClosure() {
  4603. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4604. var NonWhitespaceRegexp = /\S/;
  4605. function isAllWhitespace(str) {
  4606. return !NonWhitespaceRegexp.test(str);
  4607. }
  4608. function appendText(textDivs, viewport, geom, styles) {
  4609. var style = styles[geom.fontName];
  4610. var textDiv = document.createElement('div');
  4611. textDivs.push(textDiv);
  4612. if (isAllWhitespace(geom.str)) {
  4613. textDiv.dataset.isWhitespace = true;
  4614. return;
  4615. }
  4616. var tx = Util.transform(viewport.transform, geom.transform);
  4617. var angle = Math.atan2(tx[1], tx[0]);
  4618. if (style.vertical) {
  4619. angle += Math.PI / 2;
  4620. }
  4621. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4622. var fontAscent = fontHeight;
  4623. if (style.ascent) {
  4624. fontAscent = style.ascent * fontAscent;
  4625. } else if (style.descent) {
  4626. fontAscent = (1 + style.descent) * fontAscent;
  4627. }
  4628. var left;
  4629. var top;
  4630. if (angle === 0) {
  4631. left = tx[4];
  4632. top = tx[5] - fontAscent;
  4633. } else {
  4634. left = tx[4] + (fontAscent * Math.sin(angle));
  4635. top = tx[5] - (fontAscent * Math.cos(angle));
  4636. }
  4637. textDiv.style.left = left + 'px';
  4638. textDiv.style.top = top + 'px';
  4639. textDiv.style.fontSize = fontHeight + 'px';
  4640. textDiv.style.fontFamily = style.fontFamily;
  4641. textDiv.textContent = geom.str;
  4642. // |fontName| is only used by the Font Inspector. This test will succeed
  4643. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4644. // not worth the effort to do a more accurate test.
  4645. if (PDFJS.pdfBug) {
  4646. textDiv.dataset.fontName = geom.fontName;
  4647. }
  4648. // Storing into dataset will convert number into string.
  4649. if (angle !== 0) {
  4650. textDiv.dataset.angle = angle * (180 / Math.PI);
  4651. }
  4652. // We don't bother scaling single-char text divs, because it has very
  4653. // little effect on text highlighting. This makes scrolling on docs with
  4654. // lots of such divs a lot faster.
  4655. if (geom.str.length > 1) {
  4656. if (style.vertical) {
  4657. textDiv.dataset.canvasWidth = geom.height * viewport.scale;
  4658. } else {
  4659. textDiv.dataset.canvasWidth = geom.width * viewport.scale;
  4660. }
  4661. }
  4662. }
  4663. function render(task) {
  4664. if (task._canceled) {
  4665. return;
  4666. }
  4667. var textLayerFrag = task._container;
  4668. var textDivs = task._textDivs;
  4669. var capability = task._capability;
  4670. var textDivsLength = textDivs.length;
  4671. // No point in rendering many divs as it would make the browser
  4672. // unusable even after the divs are rendered.
  4673. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4674. capability.resolve();
  4675. return;
  4676. }
  4677. var canvas = document.createElement('canvas');
  4678. canvas.mozOpaque = true;
  4679. var ctx = canvas.getContext('2d', {alpha: false});
  4680. var lastFontSize;
  4681. var lastFontFamily;
  4682. for (var i = 0; i < textDivsLength; i++) {
  4683. var textDiv = textDivs[i];
  4684. if (textDiv.dataset.isWhitespace !== undefined) {
  4685. continue;
  4686. }
  4687. var fontSize = textDiv.style.fontSize;
  4688. var fontFamily = textDiv.style.fontFamily;
  4689. // Only build font string and set to context if different from last.
  4690. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4691. ctx.font = fontSize + ' ' + fontFamily;
  4692. lastFontSize = fontSize;
  4693. lastFontFamily = fontFamily;
  4694. }
  4695. var width = ctx.measureText(textDiv.textContent).width;
  4696. if (width > 0) {
  4697. textLayerFrag.appendChild(textDiv);
  4698. var transform;
  4699. if (textDiv.dataset.canvasWidth !== undefined) {
  4700. // Dataset values come of type string.
  4701. var textScale = textDiv.dataset.canvasWidth / width;
  4702. transform = 'scaleX(' + textScale + ')';
  4703. } else {
  4704. transform = '';
  4705. }
  4706. var rotation = textDiv.dataset.angle;
  4707. if (rotation) {
  4708. transform = 'rotate(' + rotation + 'deg) ' + transform;
  4709. }
  4710. if (transform) {
  4711. CustomStyle.setProp('transform' , textDiv, transform);
  4712. }
  4713. }
  4714. }
  4715. capability.resolve();
  4716. }
  4717. /**
  4718. * Text layer rendering task.
  4719. *
  4720. * @param {TextContent} textContent
  4721. * @param {HTMLElement} container
  4722. * @param {PDFJS.PageViewport} viewport
  4723. * @param {Array} textDivs
  4724. * @private
  4725. */
  4726. function TextLayerRenderTask(textContent, container, viewport, textDivs) {
  4727. this._textContent = textContent;
  4728. this._container = container;
  4729. this._viewport = viewport;
  4730. textDivs = textDivs || [];
  4731. this._textDivs = textDivs;
  4732. this._canceled = false;
  4733. this._capability = createPromiseCapability();
  4734. this._renderTimer = null;
  4735. }
  4736. TextLayerRenderTask.prototype = {
  4737. get promise() {
  4738. return this._capability.promise;
  4739. },
  4740. cancel: function TextLayer_cancel() {
  4741. this._canceled = true;
  4742. if (this._renderTimer !== null) {
  4743. clearTimeout(this._renderTimer);
  4744. this._renderTimer = null;
  4745. }
  4746. this._capability.reject('canceled');
  4747. },
  4748. _render: function TextLayer_render(timeout) {
  4749. var textItems = this._textContent.items;
  4750. var styles = this._textContent.styles;
  4751. var textDivs = this._textDivs;
  4752. var viewport = this._viewport;
  4753. for (var i = 0, len = textItems.length; i < len; i++) {
  4754. appendText(textDivs, viewport, textItems[i], styles);
  4755. }
  4756. if (!timeout) { // Render right away
  4757. render(this);
  4758. } else { // Schedule
  4759. var self = this;
  4760. this._renderTimer = setTimeout(function() {
  4761. render(self);
  4762. self._renderTimer = null;
  4763. }, timeout);
  4764. }
  4765. }
  4766. };
  4767. /**
  4768. * Starts rendering of the text layer.
  4769. *
  4770. * @param {TextLayerRenderParameters} renderParameters
  4771. * @returns {TextLayerRenderTask}
  4772. */
  4773. function renderTextLayer(renderParameters) {
  4774. var task = new TextLayerRenderTask(renderParameters.textContent,
  4775. renderParameters.container,
  4776. renderParameters.viewport,
  4777. renderParameters.textDivs);
  4778. task._render(renderParameters.timeout);
  4779. return task;
  4780. }
  4781. return renderTextLayer;
  4782. })();
  4783. PDFJS.renderTextLayer = renderTextLayer;
  4784. exports.renderTextLayer = renderTextLayer;
  4785. }));
  4786. (function (root, factory) {
  4787. {
  4788. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil);
  4789. }
  4790. }(this, function (exports, sharedUtil) {
  4791. var shadow = sharedUtil.shadow;
  4792. var WebGLUtils = (function WebGLUtilsClosure() {
  4793. function loadShader(gl, code, shaderType) {
  4794. var shader = gl.createShader(shaderType);
  4795. gl.shaderSource(shader, code);
  4796. gl.compileShader(shader);
  4797. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4798. if (!compiled) {
  4799. var errorMsg = gl.getShaderInfoLog(shader);
  4800. throw new Error('Error during shader compilation: ' + errorMsg);
  4801. }
  4802. return shader;
  4803. }
  4804. function createVertexShader(gl, code) {
  4805. return loadShader(gl, code, gl.VERTEX_SHADER);
  4806. }
  4807. function createFragmentShader(gl, code) {
  4808. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4809. }
  4810. function createProgram(gl, shaders) {
  4811. var program = gl.createProgram();
  4812. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4813. gl.attachShader(program, shaders[i]);
  4814. }
  4815. gl.linkProgram(program);
  4816. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4817. if (!linked) {
  4818. var errorMsg = gl.getProgramInfoLog(program);
  4819. throw new Error('Error during program linking: ' + errorMsg);
  4820. }
  4821. return program;
  4822. }
  4823. function createTexture(gl, image, textureId) {
  4824. gl.activeTexture(textureId);
  4825. var texture = gl.createTexture();
  4826. gl.bindTexture(gl.TEXTURE_2D, texture);
  4827. // Set the parameters so we can render any size image.
  4828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4829. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4832. // Upload the image into the texture.
  4833. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4834. return texture;
  4835. }
  4836. var currentGL, currentCanvas;
  4837. function generateGL() {
  4838. if (currentGL) {
  4839. return;
  4840. }
  4841. currentCanvas = document.createElement('canvas');
  4842. currentGL = currentCanvas.getContext('webgl',
  4843. { premultipliedalpha: false });
  4844. }
  4845. var smaskVertexShaderCode = '\
  4846. attribute vec2 a_position; \
  4847. attribute vec2 a_texCoord; \
  4848. \
  4849. uniform vec2 u_resolution; \
  4850. \
  4851. varying vec2 v_texCoord; \
  4852. \
  4853. void main() { \
  4854. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4855. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4856. \
  4857. v_texCoord = a_texCoord; \
  4858. } ';
  4859. var smaskFragmentShaderCode = '\
  4860. precision mediump float; \
  4861. \
  4862. uniform vec4 u_backdrop; \
  4863. uniform int u_subtype; \
  4864. uniform sampler2D u_image; \
  4865. uniform sampler2D u_mask; \
  4866. \
  4867. varying vec2 v_texCoord; \
  4868. \
  4869. void main() { \
  4870. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4871. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4872. if (u_backdrop.a > 0.0) { \
  4873. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4874. u_backdrop.rgb * (1.0 - maskColor.a); \
  4875. } \
  4876. float lum; \
  4877. if (u_subtype == 0) { \
  4878. lum = maskColor.a; \
  4879. } else { \
  4880. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4881. maskColor.b * 0.11; \
  4882. } \
  4883. imageColor.a *= lum; \
  4884. imageColor.rgb *= imageColor.a; \
  4885. gl_FragColor = imageColor; \
  4886. } ';
  4887. var smaskCache = null;
  4888. function initSmaskGL() {
  4889. var canvas, gl;
  4890. generateGL();
  4891. canvas = currentCanvas;
  4892. currentCanvas = null;
  4893. gl = currentGL;
  4894. currentGL = null;
  4895. // setup a GLSL program
  4896. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4897. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4898. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4899. gl.useProgram(program);
  4900. var cache = {};
  4901. cache.gl = gl;
  4902. cache.canvas = canvas;
  4903. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4904. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4905. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4906. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4907. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4908. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4909. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4910. // provide texture coordinates for the rectangle.
  4911. var texCoordBuffer = gl.createBuffer();
  4912. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4913. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4914. 0.0, 0.0,
  4915. 1.0, 0.0,
  4916. 0.0, 1.0,
  4917. 0.0, 1.0,
  4918. 1.0, 0.0,
  4919. 1.0, 1.0]), gl.STATIC_DRAW);
  4920. gl.enableVertexAttribArray(texCoordLocation);
  4921. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4922. gl.uniform1i(texLayerLocation, 0);
  4923. gl.uniform1i(texMaskLocation, 1);
  4924. smaskCache = cache;
  4925. }
  4926. function composeSMask(layer, mask, properties) {
  4927. var width = layer.width, height = layer.height;
  4928. if (!smaskCache) {
  4929. initSmaskGL();
  4930. }
  4931. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4932. canvas.width = width;
  4933. canvas.height = height;
  4934. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4935. gl.uniform2f(cache.resolutionLocation, width, height);
  4936. if (properties.backdrop) {
  4937. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4938. properties.backdrop[1], properties.backdrop[2], 1);
  4939. } else {
  4940. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4941. }
  4942. gl.uniform1i(cache.subtypeLocation,
  4943. properties.subtype === 'Luminosity' ? 1 : 0);
  4944. // Create a textures
  4945. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4946. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4947. // Create a buffer and put a single clipspace rectangle in
  4948. // it (2 triangles)
  4949. var buffer = gl.createBuffer();
  4950. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4951. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4952. 0, 0,
  4953. width, 0,
  4954. 0, height,
  4955. 0, height,
  4956. width, 0,
  4957. width, height]), gl.STATIC_DRAW);
  4958. gl.enableVertexAttribArray(cache.positionLocation);
  4959. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4960. // draw
  4961. gl.clearColor(0, 0, 0, 0);
  4962. gl.enable(gl.BLEND);
  4963. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4964. gl.clear(gl.COLOR_BUFFER_BIT);
  4965. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4966. gl.flush();
  4967. gl.deleteTexture(texture);
  4968. gl.deleteTexture(maskTexture);
  4969. gl.deleteBuffer(buffer);
  4970. return canvas;
  4971. }
  4972. var figuresVertexShaderCode = '\
  4973. attribute vec2 a_position; \
  4974. attribute vec3 a_color; \
  4975. \
  4976. uniform vec2 u_resolution; \
  4977. uniform vec2 u_scale; \
  4978. uniform vec2 u_offset; \
  4979. \
  4980. varying vec4 v_color; \
  4981. \
  4982. void main() { \
  4983. vec2 position = (a_position + u_offset) * u_scale; \
  4984. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  4985. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4986. \
  4987. v_color = vec4(a_color / 255.0, 1.0); \
  4988. } ';
  4989. var figuresFragmentShaderCode = '\
  4990. precision mediump float; \
  4991. \
  4992. varying vec4 v_color; \
  4993. \
  4994. void main() { \
  4995. gl_FragColor = v_color; \
  4996. } ';
  4997. var figuresCache = null;
  4998. function initFiguresGL() {
  4999. var canvas, gl;
  5000. generateGL();
  5001. canvas = currentCanvas;
  5002. currentCanvas = null;
  5003. gl = currentGL;
  5004. currentGL = null;
  5005. // setup a GLSL program
  5006. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5007. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5008. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5009. gl.useProgram(program);
  5010. var cache = {};
  5011. cache.gl = gl;
  5012. cache.canvas = canvas;
  5013. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5014. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5015. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5016. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5017. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5018. figuresCache = cache;
  5019. }
  5020. function drawFigures(width, height, backgroundColor, figures, context) {
  5021. if (!figuresCache) {
  5022. initFiguresGL();
  5023. }
  5024. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5025. canvas.width = width;
  5026. canvas.height = height;
  5027. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5028. gl.uniform2f(cache.resolutionLocation, width, height);
  5029. // count triangle points
  5030. var count = 0;
  5031. var i, ii, rows;
  5032. for (i = 0, ii = figures.length; i < ii; i++) {
  5033. switch (figures[i].type) {
  5034. case 'lattice':
  5035. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5036. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5037. break;
  5038. case 'triangles':
  5039. count += figures[i].coords.length;
  5040. break;
  5041. }
  5042. }
  5043. // transfer data
  5044. var coords = new Float32Array(count * 2);
  5045. var colors = new Uint8Array(count * 3);
  5046. var coordsMap = context.coords, colorsMap = context.colors;
  5047. var pIndex = 0, cIndex = 0;
  5048. for (i = 0, ii = figures.length; i < ii; i++) {
  5049. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5050. switch (figure.type) {
  5051. case 'lattice':
  5052. var cols = figure.verticesPerRow;
  5053. rows = (ps.length / cols) | 0;
  5054. for (var row = 1; row < rows; row++) {
  5055. var offset = row * cols + 1;
  5056. for (var col = 1; col < cols; col++, offset++) {
  5057. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5058. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5059. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5060. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5061. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5062. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5063. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5064. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5065. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5066. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5067. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5068. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5069. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5070. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5071. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5072. coords[pIndex + 6] = coords[pIndex + 2];
  5073. coords[pIndex + 7] = coords[pIndex + 3];
  5074. coords[pIndex + 8] = coords[pIndex + 4];
  5075. coords[pIndex + 9] = coords[pIndex + 5];
  5076. coords[pIndex + 10] = coordsMap[ps[offset]];
  5077. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5078. colors[cIndex + 9] = colors[cIndex + 3];
  5079. colors[cIndex + 10] = colors[cIndex + 4];
  5080. colors[cIndex + 11] = colors[cIndex + 5];
  5081. colors[cIndex + 12] = colors[cIndex + 6];
  5082. colors[cIndex + 13] = colors[cIndex + 7];
  5083. colors[cIndex + 14] = colors[cIndex + 8];
  5084. colors[cIndex + 15] = colorsMap[cs[offset]];
  5085. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5086. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5087. pIndex += 12;
  5088. cIndex += 18;
  5089. }
  5090. }
  5091. break;
  5092. case 'triangles':
  5093. for (var j = 0, jj = ps.length; j < jj; j++) {
  5094. coords[pIndex] = coordsMap[ps[j]];
  5095. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5096. colors[cIndex] = colorsMap[cs[j]];
  5097. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5098. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5099. pIndex += 2;
  5100. cIndex += 3;
  5101. }
  5102. break;
  5103. }
  5104. }
  5105. // draw
  5106. if (backgroundColor) {
  5107. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5108. backgroundColor[2] / 255, 1.0);
  5109. } else {
  5110. gl.clearColor(0, 0, 0, 0);
  5111. }
  5112. gl.clear(gl.COLOR_BUFFER_BIT);
  5113. var coordsBuffer = gl.createBuffer();
  5114. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5115. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5116. gl.enableVertexAttribArray(cache.positionLocation);
  5117. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5118. var colorsBuffer = gl.createBuffer();
  5119. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5120. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5121. gl.enableVertexAttribArray(cache.colorLocation);
  5122. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5123. 0, 0);
  5124. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5125. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5126. gl.drawArrays(gl.TRIANGLES, 0, count);
  5127. gl.flush();
  5128. gl.deleteBuffer(coordsBuffer);
  5129. gl.deleteBuffer(colorsBuffer);
  5130. return canvas;
  5131. }
  5132. function cleanup() {
  5133. if (smaskCache && smaskCache.canvas) {
  5134. smaskCache.canvas.width = 0;
  5135. smaskCache.canvas.height = 0;
  5136. }
  5137. if (figuresCache && figuresCache.canvas) {
  5138. figuresCache.canvas.width = 0;
  5139. figuresCache.canvas.height = 0;
  5140. }
  5141. smaskCache = null;
  5142. figuresCache = null;
  5143. }
  5144. return {
  5145. get isEnabled() {
  5146. if (PDFJS.disableWebGL) {
  5147. return false;
  5148. }
  5149. var enabled = false;
  5150. try {
  5151. generateGL();
  5152. enabled = !!currentGL;
  5153. } catch (e) { }
  5154. return shadow(this, 'isEnabled', enabled);
  5155. },
  5156. composeSMask: composeSMask,
  5157. drawFigures: drawFigures,
  5158. clear: cleanup
  5159. };
  5160. })();
  5161. exports.WebGLUtils = WebGLUtils;
  5162. }));
  5163. (function (root, factory) {
  5164. {
  5165. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5166. root.pdfjsDisplayWebGL);
  5167. }
  5168. }(this, function (exports, sharedUtil, displayWebGL) {
  5169. var Util = sharedUtil.Util;
  5170. var info = sharedUtil.info;
  5171. var isArray = sharedUtil.isArray;
  5172. var error = sharedUtil.error;
  5173. var WebGLUtils = displayWebGL.WebGLUtils;
  5174. var ShadingIRs = {};
  5175. ShadingIRs.RadialAxial = {
  5176. fromIR: function RadialAxial_fromIR(raw) {
  5177. var type = raw[1];
  5178. var colorStops = raw[2];
  5179. var p0 = raw[3];
  5180. var p1 = raw[4];
  5181. var r0 = raw[5];
  5182. var r1 = raw[6];
  5183. return {
  5184. type: 'Pattern',
  5185. getPattern: function RadialAxial_getPattern(ctx) {
  5186. var grad;
  5187. if (type === 'axial') {
  5188. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5189. } else if (type === 'radial') {
  5190. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5191. }
  5192. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5193. var c = colorStops[i];
  5194. grad.addColorStop(c[0], c[1]);
  5195. }
  5196. return grad;
  5197. }
  5198. };
  5199. }
  5200. };
  5201. var createMeshCanvas = (function createMeshCanvasClosure() {
  5202. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5203. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5204. var coords = context.coords, colors = context.colors;
  5205. var bytes = data.data, rowSize = data.width * 4;
  5206. var tmp;
  5207. if (coords[p1 + 1] > coords[p2 + 1]) {
  5208. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5209. }
  5210. if (coords[p2 + 1] > coords[p3 + 1]) {
  5211. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5212. }
  5213. if (coords[p1 + 1] > coords[p2 + 1]) {
  5214. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5215. }
  5216. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5217. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5218. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5219. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5220. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5221. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5222. if (y1 >= y3) {
  5223. return;
  5224. }
  5225. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5226. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5227. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5228. var minY = Math.round(y1), maxY = Math.round(y3);
  5229. var xa, car, cag, cab;
  5230. var xb, cbr, cbg, cbb;
  5231. var k;
  5232. for (var y = minY; y <= maxY; y++) {
  5233. if (y < y2) {
  5234. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5235. xa = x1 - (x1 - x2) * k;
  5236. car = c1r - (c1r - c2r) * k;
  5237. cag = c1g - (c1g - c2g) * k;
  5238. cab = c1b - (c1b - c2b) * k;
  5239. } else {
  5240. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5241. xa = x2 - (x2 - x3) * k;
  5242. car = c2r - (c2r - c3r) * k;
  5243. cag = c2g - (c2g - c3g) * k;
  5244. cab = c2b - (c2b - c3b) * k;
  5245. }
  5246. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5247. xb = x1 - (x1 - x3) * k;
  5248. cbr = c1r - (c1r - c3r) * k;
  5249. cbg = c1g - (c1g - c3g) * k;
  5250. cbb = c1b - (c1b - c3b) * k;
  5251. var x1_ = Math.round(Math.min(xa, xb));
  5252. var x2_ = Math.round(Math.max(xa, xb));
  5253. var j = rowSize * y + x1_ * 4;
  5254. for (var x = x1_; x <= x2_; x++) {
  5255. k = (xa - x) / (xa - xb);
  5256. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5257. bytes[j++] = (car - (car - cbr) * k) | 0;
  5258. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5259. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5260. bytes[j++] = 255;
  5261. }
  5262. }
  5263. }
  5264. function drawFigure(data, figure, context) {
  5265. var ps = figure.coords;
  5266. var cs = figure.colors;
  5267. var i, ii;
  5268. switch (figure.type) {
  5269. case 'lattice':
  5270. var verticesPerRow = figure.verticesPerRow;
  5271. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5272. var cols = verticesPerRow - 1;
  5273. for (i = 0; i < rows; i++) {
  5274. var q = i * verticesPerRow;
  5275. for (var j = 0; j < cols; j++, q++) {
  5276. drawTriangle(data, context,
  5277. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5278. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5279. drawTriangle(data, context,
  5280. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5281. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5282. }
  5283. }
  5284. break;
  5285. case 'triangles':
  5286. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5287. drawTriangle(data, context,
  5288. ps[i], ps[i + 1], ps[i + 2],
  5289. cs[i], cs[i + 1], cs[i + 2]);
  5290. }
  5291. break;
  5292. default:
  5293. error('illigal figure');
  5294. break;
  5295. }
  5296. }
  5297. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5298. backgroundColor, cachedCanvases) {
  5299. // we will increase scale on some weird factor to let antialiasing take
  5300. // care of "rough" edges
  5301. var EXPECTED_SCALE = 1.1;
  5302. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5303. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5304. var offsetX = Math.floor(bounds[0]);
  5305. var offsetY = Math.floor(bounds[1]);
  5306. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5307. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5308. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5309. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5310. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5311. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5312. var scaleX = boundsWidth / width;
  5313. var scaleY = boundsHeight / height;
  5314. var context = {
  5315. coords: coords,
  5316. colors: colors,
  5317. offsetX: -offsetX,
  5318. offsetY: -offsetY,
  5319. scaleX: 1 / scaleX,
  5320. scaleY: 1 / scaleY
  5321. };
  5322. var canvas, tmpCanvas, i, ii;
  5323. if (WebGLUtils.isEnabled) {
  5324. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5325. figures, context);
  5326. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5327. tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
  5328. tmpCanvas.context.drawImage(canvas, 0, 0);
  5329. canvas = tmpCanvas.canvas;
  5330. } else {
  5331. tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
  5332. var tmpCtx = tmpCanvas.context;
  5333. var data = tmpCtx.createImageData(width, height);
  5334. if (backgroundColor) {
  5335. var bytes = data.data;
  5336. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5337. bytes[i] = backgroundColor[0];
  5338. bytes[i + 1] = backgroundColor[1];
  5339. bytes[i + 2] = backgroundColor[2];
  5340. bytes[i + 3] = 255;
  5341. }
  5342. }
  5343. for (i = 0; i < figures.length; i++) {
  5344. drawFigure(data, figures[i], context);
  5345. }
  5346. tmpCtx.putImageData(data, 0, 0);
  5347. canvas = tmpCanvas.canvas;
  5348. }
  5349. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5350. scaleX: scaleX, scaleY: scaleY};
  5351. }
  5352. return createMeshCanvas;
  5353. })();
  5354. ShadingIRs.Mesh = {
  5355. fromIR: function Mesh_fromIR(raw) {
  5356. //var type = raw[1];
  5357. var coords = raw[2];
  5358. var colors = raw[3];
  5359. var figures = raw[4];
  5360. var bounds = raw[5];
  5361. var matrix = raw[6];
  5362. //var bbox = raw[7];
  5363. var background = raw[8];
  5364. return {
  5365. type: 'Pattern',
  5366. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5367. var scale;
  5368. if (shadingFill) {
  5369. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5370. } else {
  5371. // Obtain scale from matrix and current transformation matrix.
  5372. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5373. if (matrix) {
  5374. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5375. scale = [scale[0] * matrixScale[0],
  5376. scale[1] * matrixScale[1]];
  5377. }
  5378. }
  5379. // Rasterizing on the main thread since sending/queue large canvases
  5380. // might cause OOM.
  5381. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5382. colors, figures, shadingFill ? null : background,
  5383. owner.cachedCanvases);
  5384. if (!shadingFill) {
  5385. ctx.setTransform.apply(ctx, owner.baseTransform);
  5386. if (matrix) {
  5387. ctx.transform.apply(ctx, matrix);
  5388. }
  5389. }
  5390. ctx.translate(temporaryPatternCanvas.offsetX,
  5391. temporaryPatternCanvas.offsetY);
  5392. ctx.scale(temporaryPatternCanvas.scaleX,
  5393. temporaryPatternCanvas.scaleY);
  5394. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5395. }
  5396. };
  5397. }
  5398. };
  5399. ShadingIRs.Dummy = {
  5400. fromIR: function Dummy_fromIR() {
  5401. return {
  5402. type: 'Pattern',
  5403. getPattern: function Dummy_fromIR_getPattern() {
  5404. return 'hotpink';
  5405. }
  5406. };
  5407. }
  5408. };
  5409. function getShadingPatternFromIR(raw) {
  5410. var shadingIR = ShadingIRs[raw[0]];
  5411. if (!shadingIR) {
  5412. error('Unknown IR type: ' + raw[0]);
  5413. }
  5414. return shadingIR.fromIR(raw);
  5415. }
  5416. var TilingPattern = (function TilingPatternClosure() {
  5417. var PaintType = {
  5418. COLORED: 1,
  5419. UNCOLORED: 2
  5420. };
  5421. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5422. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5423. this.operatorList = IR[2];
  5424. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5425. this.bbox = IR[4];
  5426. this.xstep = IR[5];
  5427. this.ystep = IR[6];
  5428. this.paintType = IR[7];
  5429. this.tilingType = IR[8];
  5430. this.color = color;
  5431. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5432. this.baseTransform = baseTransform;
  5433. this.type = 'Pattern';
  5434. this.ctx = ctx;
  5435. }
  5436. TilingPattern.prototype = {
  5437. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5438. var operatorList = this.operatorList;
  5439. var bbox = this.bbox;
  5440. var xstep = this.xstep;
  5441. var ystep = this.ystep;
  5442. var paintType = this.paintType;
  5443. var tilingType = this.tilingType;
  5444. var color = this.color;
  5445. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5446. info('TilingType: ' + tilingType);
  5447. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5448. var topLeft = [x0, y0];
  5449. // we want the canvas to be as large as the step size
  5450. var botRight = [x0 + xstep, y0 + ystep];
  5451. var width = botRight[0] - topLeft[0];
  5452. var height = botRight[1] - topLeft[1];
  5453. // Obtain scale from matrix and current transformation matrix.
  5454. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5455. var curMatrixScale = Util.singularValueDecompose2dScale(
  5456. this.baseTransform);
  5457. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5458. matrixScale[1] * curMatrixScale[1]];
  5459. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5460. // Use width and height values that are as close as possible to the end
  5461. // result when the pattern is used. Too low value makes the pattern look
  5462. // blurry. Too large value makes it look too crispy.
  5463. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5464. MAX_PATTERN_SIZE);
  5465. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5466. MAX_PATTERN_SIZE);
  5467. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5468. width, height, true);
  5469. var tmpCtx = tmpCanvas.context;
  5470. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5471. graphics.groupLevel = owner.groupLevel;
  5472. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5473. this.setScale(width, height, xstep, ystep);
  5474. this.transformToScale(graphics);
  5475. // transform coordinates to pattern space
  5476. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5477. graphics.transform.apply(graphics, tmpTranslate);
  5478. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5479. graphics.executeOperatorList(operatorList);
  5480. return tmpCanvas.canvas;
  5481. },
  5482. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5483. this.scale = [width / xstep, height / ystep];
  5484. },
  5485. transformToScale: function TilingPattern_transformToScale(graphics) {
  5486. var scale = this.scale;
  5487. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5488. graphics.transform.apply(graphics, tmpScale);
  5489. },
  5490. scaleToContext: function TilingPattern_scaleToContext() {
  5491. var scale = this.scale;
  5492. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5493. },
  5494. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5495. if (bbox && isArray(bbox) && bbox.length === 4) {
  5496. var bboxWidth = x1 - x0;
  5497. var bboxHeight = y1 - y0;
  5498. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5499. graphics.clip();
  5500. graphics.endPath();
  5501. }
  5502. },
  5503. setFillAndStrokeStyleToContext:
  5504. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5505. switch (paintType) {
  5506. case PaintType.COLORED:
  5507. var ctx = this.ctx;
  5508. context.fillStyle = ctx.fillStyle;
  5509. context.strokeStyle = ctx.strokeStyle;
  5510. break;
  5511. case PaintType.UNCOLORED:
  5512. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5513. context.fillStyle = cssColor;
  5514. context.strokeStyle = cssColor;
  5515. break;
  5516. default:
  5517. error('Unsupported paint type: ' + paintType);
  5518. }
  5519. },
  5520. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5521. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5522. ctx = this.ctx;
  5523. ctx.setTransform.apply(ctx, this.baseTransform);
  5524. ctx.transform.apply(ctx, this.matrix);
  5525. this.scaleToContext();
  5526. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5527. }
  5528. };
  5529. return TilingPattern;
  5530. })();
  5531. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  5532. exports.TilingPattern = TilingPattern;
  5533. }));
  5534. (function (root, factory) {
  5535. {
  5536. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  5537. root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  5538. }
  5539. }(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) {
  5540. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  5541. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  5542. var ImageKind = sharedUtil.ImageKind;
  5543. var OPS = sharedUtil.OPS;
  5544. var TextRenderingMode = sharedUtil.TextRenderingMode;
  5545. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  5546. var Util = sharedUtil.Util;
  5547. var assert = sharedUtil.assert;
  5548. var info = sharedUtil.info;
  5549. var isNum = sharedUtil.isNum;
  5550. var isArray = sharedUtil.isArray;
  5551. var error = sharedUtil.error;
  5552. var shadow = sharedUtil.shadow;
  5553. var warn = sharedUtil.warn;
  5554. var TilingPattern = displayPatternHelper.TilingPattern;
  5555. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  5556. var WebGLUtils = displayWebGL.WebGLUtils;
  5557. // <canvas> contexts store most of the state we need natively.
  5558. // However, PDF needs a bit more state, which we store here.
  5559. // Minimal font size that would be used during canvas fillText operations.
  5560. var MIN_FONT_SIZE = 16;
  5561. // Maximum font size that would be used during canvas fillText operations.
  5562. var MAX_FONT_SIZE = 100;
  5563. var MAX_GROUP_SIZE = 4096;
  5564. // Heuristic value used when enforcing minimum line widths.
  5565. var MIN_WIDTH_FACTOR = 0.65;
  5566. var COMPILE_TYPE3_GLYPHS = true;
  5567. var MAX_SIZE_TO_COMPILE = 1000;
  5568. var FULL_CHUNK_HEIGHT = 16;
  5569. function createScratchCanvas(width, height) {
  5570. var canvas = document.createElement('canvas');
  5571. canvas.width = width;
  5572. canvas.height = height;
  5573. return canvas;
  5574. }
  5575. function addContextCurrentTransform(ctx) {
  5576. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  5577. if (!ctx.mozCurrentTransform) {
  5578. ctx._originalSave = ctx.save;
  5579. ctx._originalRestore = ctx.restore;
  5580. ctx._originalRotate = ctx.rotate;
  5581. ctx._originalScale = ctx.scale;
  5582. ctx._originalTranslate = ctx.translate;
  5583. ctx._originalTransform = ctx.transform;
  5584. ctx._originalSetTransform = ctx.setTransform;
  5585. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  5586. ctx._transformStack = [];
  5587. Object.defineProperty(ctx, 'mozCurrentTransform', {
  5588. get: function getCurrentTransform() {
  5589. return this._transformMatrix;
  5590. }
  5591. });
  5592. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  5593. get: function getCurrentTransformInverse() {
  5594. // Calculation done using WolframAlpha:
  5595. // http://www.wolframalpha.com/input/?
  5596. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  5597. var m = this._transformMatrix;
  5598. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  5599. var ad_bc = a * d - b * c;
  5600. var bc_ad = b * c - a * d;
  5601. return [
  5602. d / ad_bc,
  5603. b / bc_ad,
  5604. c / bc_ad,
  5605. a / ad_bc,
  5606. (d * e - c * f) / bc_ad,
  5607. (b * e - a * f) / ad_bc
  5608. ];
  5609. }
  5610. });
  5611. ctx.save = function ctxSave() {
  5612. var old = this._transformMatrix;
  5613. this._transformStack.push(old);
  5614. this._transformMatrix = old.slice(0, 6);
  5615. this._originalSave();
  5616. };
  5617. ctx.restore = function ctxRestore() {
  5618. var prev = this._transformStack.pop();
  5619. if (prev) {
  5620. this._transformMatrix = prev;
  5621. this._originalRestore();
  5622. }
  5623. };
  5624. ctx.translate = function ctxTranslate(x, y) {
  5625. var m = this._transformMatrix;
  5626. m[4] = m[0] * x + m[2] * y + m[4];
  5627. m[5] = m[1] * x + m[3] * y + m[5];
  5628. this._originalTranslate(x, y);
  5629. };
  5630. ctx.scale = function ctxScale(x, y) {
  5631. var m = this._transformMatrix;
  5632. m[0] = m[0] * x;
  5633. m[1] = m[1] * x;
  5634. m[2] = m[2] * y;
  5635. m[3] = m[3] * y;
  5636. this._originalScale(x, y);
  5637. };
  5638. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  5639. var m = this._transformMatrix;
  5640. this._transformMatrix = [
  5641. m[0] * a + m[2] * b,
  5642. m[1] * a + m[3] * b,
  5643. m[0] * c + m[2] * d,
  5644. m[1] * c + m[3] * d,
  5645. m[0] * e + m[2] * f + m[4],
  5646. m[1] * e + m[3] * f + m[5]
  5647. ];
  5648. ctx._originalTransform(a, b, c, d, e, f);
  5649. };
  5650. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  5651. this._transformMatrix = [a, b, c, d, e, f];
  5652. ctx._originalSetTransform(a, b, c, d, e, f);
  5653. };
  5654. ctx.rotate = function ctxRotate(angle) {
  5655. var cosValue = Math.cos(angle);
  5656. var sinValue = Math.sin(angle);
  5657. var m = this._transformMatrix;
  5658. this._transformMatrix = [
  5659. m[0] * cosValue + m[2] * sinValue,
  5660. m[1] * cosValue + m[3] * sinValue,
  5661. m[0] * (-sinValue) + m[2] * cosValue,
  5662. m[1] * (-sinValue) + m[3] * cosValue,
  5663. m[4],
  5664. m[5]
  5665. ];
  5666. this._originalRotate(angle);
  5667. };
  5668. }
  5669. }
  5670. var CachedCanvases = (function CachedCanvasesClosure() {
  5671. function CachedCanvases() {
  5672. this.cache = Object.create(null);
  5673. }
  5674. CachedCanvases.prototype = {
  5675. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  5676. trackTransform) {
  5677. var canvasEntry;
  5678. if (this.cache[id] !== undefined) {
  5679. canvasEntry = this.cache[id];
  5680. canvasEntry.canvas.width = width;
  5681. canvasEntry.canvas.height = height;
  5682. // reset canvas transform for emulated mozCurrentTransform, if needed
  5683. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  5684. } else {
  5685. var canvas = createScratchCanvas(width, height);
  5686. var ctx = canvas.getContext('2d');
  5687. if (trackTransform) {
  5688. addContextCurrentTransform(ctx);
  5689. }
  5690. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  5691. }
  5692. return canvasEntry;
  5693. },
  5694. clear: function () {
  5695. for (var id in this.cache) {
  5696. var canvasEntry = this.cache[id];
  5697. // Zeroing the width and height causes Firefox to release graphics
  5698. // resources immediately, which can greatly reduce memory consumption.
  5699. canvasEntry.canvas.width = 0;
  5700. canvasEntry.canvas.height = 0;
  5701. delete this.cache[id];
  5702. }
  5703. }
  5704. };
  5705. return CachedCanvases;
  5706. })();
  5707. function compileType3Glyph(imgData) {
  5708. var POINT_TO_PROCESS_LIMIT = 1000;
  5709. var width = imgData.width, height = imgData.height;
  5710. var i, j, j0, width1 = width + 1;
  5711. var points = new Uint8Array(width1 * (height + 1));
  5712. var POINT_TYPES =
  5713. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  5714. // decodes bit-packed mask data
  5715. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  5716. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  5717. for (i = 0, ii = data0.length; i < ii; i++) {
  5718. var mask = 128, elem = data0[i];
  5719. while (mask > 0) {
  5720. data[pos++] = (elem & mask) ? 0 : 255;
  5721. mask >>= 1;
  5722. }
  5723. }
  5724. // finding iteresting points: every point is located between mask pixels,
  5725. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  5726. // will have flags assigned based on neighboring mask pixels:
  5727. // 4 | 8
  5728. // --P--
  5729. // 2 | 1
  5730. // We are interested only in points with the flags:
  5731. // - outside corners: 1, 2, 4, 8;
  5732. // - inside corners: 7, 11, 13, 14;
  5733. // - and, intersections: 5, 10.
  5734. var count = 0;
  5735. pos = 0;
  5736. if (data[pos] !== 0) {
  5737. points[0] = 1;
  5738. ++count;
  5739. }
  5740. for (j = 1; j < width; j++) {
  5741. if (data[pos] !== data[pos + 1]) {
  5742. points[j] = data[pos] ? 2 : 1;
  5743. ++count;
  5744. }
  5745. pos++;
  5746. }
  5747. if (data[pos] !== 0) {
  5748. points[j] = 2;
  5749. ++count;
  5750. }
  5751. for (i = 1; i < height; i++) {
  5752. pos = i * lineSize;
  5753. j0 = i * width1;
  5754. if (data[pos - lineSize] !== data[pos]) {
  5755. points[j0] = data[pos] ? 1 : 8;
  5756. ++count;
  5757. }
  5758. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  5759. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  5760. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5761. for (j = 1; j < width; j++) {
  5762. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  5763. (data[pos - lineSize + 1] ? 8 : 0);
  5764. if (POINT_TYPES[sum]) {
  5765. points[j0 + j] = POINT_TYPES[sum];
  5766. ++count;
  5767. }
  5768. pos++;
  5769. }
  5770. if (data[pos - lineSize] !== data[pos]) {
  5771. points[j0 + j] = data[pos] ? 2 : 4;
  5772. ++count;
  5773. }
  5774. if (count > POINT_TO_PROCESS_LIMIT) {
  5775. return null;
  5776. }
  5777. }
  5778. pos = lineSize * (height - 1);
  5779. j0 = i * width1;
  5780. if (data[pos] !== 0) {
  5781. points[j0] = 8;
  5782. ++count;
  5783. }
  5784. for (j = 1; j < width; j++) {
  5785. if (data[pos] !== data[pos + 1]) {
  5786. points[j0 + j] = data[pos] ? 4 : 8;
  5787. ++count;
  5788. }
  5789. pos++;
  5790. }
  5791. if (data[pos] !== 0) {
  5792. points[j0 + j] = 4;
  5793. ++count;
  5794. }
  5795. if (count > POINT_TO_PROCESS_LIMIT) {
  5796. return null;
  5797. }
  5798. // building outlines
  5799. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5800. var outlines = [];
  5801. for (i = 0; count && i <= height; i++) {
  5802. var p = i * width1;
  5803. var end = p + width;
  5804. while (p < end && !points[p]) {
  5805. p++;
  5806. }
  5807. if (p === end) {
  5808. continue;
  5809. }
  5810. var coords = [p % width1, i];
  5811. var type = points[p], p0 = p, pp;
  5812. do {
  5813. var step = steps[type];
  5814. do {
  5815. p += step;
  5816. } while (!points[p]);
  5817. pp = points[p];
  5818. if (pp !== 5 && pp !== 10) {
  5819. // set new direction
  5820. type = pp;
  5821. // delete mark
  5822. points[p] = 0;
  5823. } else { // type is 5 or 10, ie, a crossing
  5824. // set new direction
  5825. type = pp & ((0x33 * type) >> 4);
  5826. // set new type for "future hit"
  5827. points[p] &= (type >> 2 | type << 2);
  5828. }
  5829. coords.push(p % width1);
  5830. coords.push((p / width1) | 0);
  5831. --count;
  5832. } while (p0 !== p);
  5833. outlines.push(coords);
  5834. --i;
  5835. }
  5836. var drawOutline = function(c) {
  5837. c.save();
  5838. // the path shall be painted in [0..1]x[0..1] space
  5839. c.scale(1 / width, -1 / height);
  5840. c.translate(0, -height);
  5841. c.beginPath();
  5842. for (var i = 0, ii = outlines.length; i < ii; i++) {
  5843. var o = outlines[i];
  5844. c.moveTo(o[0], o[1]);
  5845. for (var j = 2, jj = o.length; j < jj; j += 2) {
  5846. c.lineTo(o[j], o[j+1]);
  5847. }
  5848. }
  5849. c.fill();
  5850. c.beginPath();
  5851. c.restore();
  5852. };
  5853. return drawOutline;
  5854. }
  5855. var CanvasExtraState = (function CanvasExtraStateClosure() {
  5856. function CanvasExtraState(old) {
  5857. // Are soft masks and alpha values shapes or opacities?
  5858. this.alphaIsShape = false;
  5859. this.fontSize = 0;
  5860. this.fontSizeScale = 1;
  5861. this.textMatrix = IDENTITY_MATRIX;
  5862. this.textMatrixScale = 1;
  5863. this.fontMatrix = FONT_IDENTITY_MATRIX;
  5864. this.leading = 0;
  5865. // Current point (in user coordinates)
  5866. this.x = 0;
  5867. this.y = 0;
  5868. // Start of text line (in text coordinates)
  5869. this.lineX = 0;
  5870. this.lineY = 0;
  5871. // Character and word spacing
  5872. this.charSpacing = 0;
  5873. this.wordSpacing = 0;
  5874. this.textHScale = 1;
  5875. this.textRenderingMode = TextRenderingMode.FILL;
  5876. this.textRise = 0;
  5877. // Default fore and background colors
  5878. this.fillColor = '#000000';
  5879. this.strokeColor = '#000000';
  5880. this.patternFill = false;
  5881. // Note: fill alpha applies to all non-stroking operations
  5882. this.fillAlpha = 1;
  5883. this.strokeAlpha = 1;
  5884. this.lineWidth = 1;
  5885. this.activeSMask = null; // nonclonable field (see the save method below)
  5886. this.old = old;
  5887. }
  5888. CanvasExtraState.prototype = {
  5889. clone: function CanvasExtraState_clone() {
  5890. return Object.create(this);
  5891. },
  5892. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  5893. this.x = x;
  5894. this.y = y;
  5895. }
  5896. };
  5897. return CanvasExtraState;
  5898. })();
  5899. var CanvasGraphics = (function CanvasGraphicsClosure() {
  5900. // Defines the time the executeOperatorList is going to be executing
  5901. // before it stops and shedules a continue of execution.
  5902. var EXECUTION_TIME = 15;
  5903. // Defines the number of steps before checking the execution time
  5904. var EXECUTION_STEPS = 10;
  5905. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  5906. this.ctx = canvasCtx;
  5907. this.current = new CanvasExtraState();
  5908. this.stateStack = [];
  5909. this.pendingClip = null;
  5910. this.pendingEOFill = false;
  5911. this.res = null;
  5912. this.xobjs = null;
  5913. this.commonObjs = commonObjs;
  5914. this.objs = objs;
  5915. this.imageLayer = imageLayer;
  5916. this.groupStack = [];
  5917. this.processingType3 = null;
  5918. // Patterns are painted relative to the initial page/form transform, see pdf
  5919. // spec 8.7.2 NOTE 1.
  5920. this.baseTransform = null;
  5921. this.baseTransformStack = [];
  5922. this.groupLevel = 0;
  5923. this.smaskStack = [];
  5924. this.smaskCounter = 0;
  5925. this.tempSMask = null;
  5926. this.cachedCanvases = new CachedCanvases();
  5927. if (canvasCtx) {
  5928. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  5929. // the transformation must already be set in canvasCtx._transformMatrix.
  5930. addContextCurrentTransform(canvasCtx);
  5931. }
  5932. this.cachedGetSinglePixelWidth = null;
  5933. }
  5934. function putBinaryImageData(ctx, imgData) {
  5935. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  5936. ctx.putImageData(imgData, 0, 0);
  5937. return;
  5938. }
  5939. // Put the image data to the canvas in chunks, rather than putting the
  5940. // whole image at once. This saves JS memory, because the ImageData object
  5941. // is smaller. It also possibly saves C++ memory within the implementation
  5942. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  5943. // the data passed to putImageData()). |n| shouldn't be too small, however,
  5944. // because too many putImageData() calls will slow things down.
  5945. //
  5946. // Note: as written, if the last chunk is partial, the putImageData() call
  5947. // will (conceptually) put pixels past the bounds of the canvas. But
  5948. // that's ok; any such pixels are ignored.
  5949. var height = imgData.height, width = imgData.width;
  5950. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5951. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5952. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5953. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5954. var srcPos = 0, destPos;
  5955. var src = imgData.data;
  5956. var dest = chunkImgData.data;
  5957. var i, j, thisChunkHeight, elemsInThisChunk;
  5958. // There are multiple forms in which the pixel data can be passed, and
  5959. // imgData.kind tells us which one this is.
  5960. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  5961. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  5962. var srcLength = src.byteLength;
  5963. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  5964. new Uint32ArrayView(dest);
  5965. var dest32DataLength = dest32.length;
  5966. var fullSrcDiff = (width + 7) >> 3;
  5967. var white = 0xFFFFFFFF;
  5968. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  5969. 0xFF000000 : 0x000000FF;
  5970. for (i = 0; i < totalChunks; i++) {
  5971. thisChunkHeight =
  5972. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5973. destPos = 0;
  5974. for (j = 0; j < thisChunkHeight; j++) {
  5975. var srcDiff = srcLength - srcPos;
  5976. var k = 0;
  5977. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  5978. var kEndUnrolled = kEnd & ~7;
  5979. var mask = 0;
  5980. var srcByte = 0;
  5981. for (; k < kEndUnrolled; k += 8) {
  5982. srcByte = src[srcPos++];
  5983. dest32[destPos++] = (srcByte & 128) ? white : black;
  5984. dest32[destPos++] = (srcByte & 64) ? white : black;
  5985. dest32[destPos++] = (srcByte & 32) ? white : black;
  5986. dest32[destPos++] = (srcByte & 16) ? white : black;
  5987. dest32[destPos++] = (srcByte & 8) ? white : black;
  5988. dest32[destPos++] = (srcByte & 4) ? white : black;
  5989. dest32[destPos++] = (srcByte & 2) ? white : black;
  5990. dest32[destPos++] = (srcByte & 1) ? white : black;
  5991. }
  5992. for (; k < kEnd; k++) {
  5993. if (mask === 0) {
  5994. srcByte = src[srcPos++];
  5995. mask = 128;
  5996. }
  5997. dest32[destPos++] = (srcByte & mask) ? white : black;
  5998. mask >>= 1;
  5999. }
  6000. }
  6001. // We ran out of input. Make all remaining pixels transparent.
  6002. while (destPos < dest32DataLength) {
  6003. dest32[destPos++] = 0;
  6004. }
  6005. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6006. }
  6007. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6008. // RGBA, 32-bits per pixel.
  6009. j = 0;
  6010. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6011. for (i = 0; i < fullChunks; i++) {
  6012. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6013. srcPos += elemsInThisChunk;
  6014. ctx.putImageData(chunkImgData, 0, j);
  6015. j += FULL_CHUNK_HEIGHT;
  6016. }
  6017. if (i < totalChunks) {
  6018. elemsInThisChunk = width * partialChunkHeight * 4;
  6019. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6020. ctx.putImageData(chunkImgData, 0, j);
  6021. }
  6022. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6023. // RGB, 24-bits per pixel.
  6024. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6025. elemsInThisChunk = width * thisChunkHeight;
  6026. for (i = 0; i < totalChunks; i++) {
  6027. if (i >= fullChunks) {
  6028. thisChunkHeight = partialChunkHeight;
  6029. elemsInThisChunk = width * thisChunkHeight;
  6030. }
  6031. destPos = 0;
  6032. for (j = elemsInThisChunk; j--;) {
  6033. dest[destPos++] = src[srcPos++];
  6034. dest[destPos++] = src[srcPos++];
  6035. dest[destPos++] = src[srcPos++];
  6036. dest[destPos++] = 255;
  6037. }
  6038. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6039. }
  6040. } else {
  6041. error('bad image kind: ' + imgData.kind);
  6042. }
  6043. }
  6044. function putBinaryImageMask(ctx, imgData) {
  6045. var height = imgData.height, width = imgData.width;
  6046. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6047. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6048. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6049. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6050. var srcPos = 0;
  6051. var src = imgData.data;
  6052. var dest = chunkImgData.data;
  6053. for (var i = 0; i < totalChunks; i++) {
  6054. var thisChunkHeight =
  6055. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6056. // Expand the mask so it can be used by the canvas. Any required
  6057. // inversion has already been handled.
  6058. var destPos = 3; // alpha component offset
  6059. for (var j = 0; j < thisChunkHeight; j++) {
  6060. var mask = 0;
  6061. for (var k = 0; k < width; k++) {
  6062. if (!mask) {
  6063. var elem = src[srcPos++];
  6064. mask = 128;
  6065. }
  6066. dest[destPos] = (elem & mask) ? 0 : 255;
  6067. destPos += 4;
  6068. mask >>= 1;
  6069. }
  6070. }
  6071. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6072. }
  6073. }
  6074. function copyCtxState(sourceCtx, destCtx) {
  6075. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6076. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6077. 'globalCompositeOperation', 'font'];
  6078. for (var i = 0, ii = properties.length; i < ii; i++) {
  6079. var property = properties[i];
  6080. if (sourceCtx[property] !== undefined) {
  6081. destCtx[property] = sourceCtx[property];
  6082. }
  6083. }
  6084. if (sourceCtx.setLineDash !== undefined) {
  6085. destCtx.setLineDash(sourceCtx.getLineDash());
  6086. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6087. } else if (sourceCtx.mozDashOffset !== undefined) {
  6088. destCtx.mozDash = sourceCtx.mozDash;
  6089. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  6090. }
  6091. }
  6092. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6093. var length = bytes.length;
  6094. for (var i = 3; i < length; i += 4) {
  6095. var alpha = bytes[i];
  6096. if (alpha === 0) {
  6097. bytes[i - 3] = r0;
  6098. bytes[i - 2] = g0;
  6099. bytes[i - 1] = b0;
  6100. } else if (alpha < 255) {
  6101. var alpha_ = 255 - alpha;
  6102. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6103. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6104. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6105. }
  6106. }
  6107. }
  6108. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6109. var length = maskData.length;
  6110. var scale = 1 / 255;
  6111. for (var i = 3; i < length; i += 4) {
  6112. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6113. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6114. }
  6115. }
  6116. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6117. var length = maskData.length;
  6118. for (var i = 3; i < length; i += 4) {
  6119. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6120. (maskData[i - 2] * 152) + // * 0.59 ....
  6121. (maskData[i - 1] * 28); // * 0.11 ....
  6122. layerData[i] = transferMap ?
  6123. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6124. (layerData[i] * y) >> 16;
  6125. }
  6126. }
  6127. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6128. subtype, backdrop, transferMap) {
  6129. var hasBackdrop = !!backdrop;
  6130. var r0 = hasBackdrop ? backdrop[0] : 0;
  6131. var g0 = hasBackdrop ? backdrop[1] : 0;
  6132. var b0 = hasBackdrop ? backdrop[2] : 0;
  6133. var composeFn;
  6134. if (subtype === 'Luminosity') {
  6135. composeFn = composeSMaskLuminosity;
  6136. } else {
  6137. composeFn = composeSMaskAlpha;
  6138. }
  6139. // processing image in chunks to save memory
  6140. var PIXELS_TO_PROCESS = 1048576;
  6141. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6142. for (var row = 0; row < height; row += chunkSize) {
  6143. var chunkHeight = Math.min(chunkSize, height - row);
  6144. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6145. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6146. if (hasBackdrop) {
  6147. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6148. }
  6149. composeFn(maskData.data, layerData.data, transferMap);
  6150. maskCtx.putImageData(layerData, 0, row);
  6151. }
  6152. }
  6153. function composeSMask(ctx, smask, layerCtx) {
  6154. var mask = smask.canvas;
  6155. var maskCtx = smask.context;
  6156. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6157. smask.offsetX, smask.offsetY);
  6158. var backdrop = smask.backdrop || null;
  6159. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6160. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6161. {subtype: smask.subtype, backdrop: backdrop});
  6162. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6163. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6164. return;
  6165. }
  6166. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6167. smask.subtype, backdrop, smask.transferMap);
  6168. ctx.drawImage(mask, 0, 0);
  6169. }
  6170. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6171. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6172. var NORMAL_CLIP = {};
  6173. var EO_CLIP = {};
  6174. CanvasGraphics.prototype = {
  6175. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6176. transparency) {
  6177. // For pdfs that use blend modes we have to clear the canvas else certain
  6178. // blend modes can look wrong since we'd be blending with a white
  6179. // backdrop. The problem with a transparent backdrop though is we then
  6180. // don't get sub pixel anti aliasing on text, creating temporary
  6181. // transparent canvas when we have blend modes.
  6182. var width = this.ctx.canvas.width;
  6183. var height = this.ctx.canvas.height;
  6184. this.ctx.save();
  6185. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6186. this.ctx.fillRect(0, 0, width, height);
  6187. this.ctx.restore();
  6188. if (transparency) {
  6189. var transparentCanvas = this.cachedCanvases.getCanvas(
  6190. 'transparent', width, height, true);
  6191. this.compositeCtx = this.ctx;
  6192. this.transparentCanvas = transparentCanvas.canvas;
  6193. this.ctx = transparentCanvas.context;
  6194. this.ctx.save();
  6195. // The transform can be applied before rendering, transferring it to
  6196. // the new canvas.
  6197. this.ctx.transform.apply(this.ctx,
  6198. this.compositeCtx.mozCurrentTransform);
  6199. }
  6200. this.ctx.save();
  6201. if (transform) {
  6202. this.ctx.transform.apply(this.ctx, transform);
  6203. }
  6204. this.ctx.transform.apply(this.ctx, viewport.transform);
  6205. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6206. if (this.imageLayer) {
  6207. this.imageLayer.beginLayout();
  6208. }
  6209. },
  6210. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6211. operatorList,
  6212. executionStartIdx, continueCallback,
  6213. stepper) {
  6214. var argsArray = operatorList.argsArray;
  6215. var fnArray = operatorList.fnArray;
  6216. var i = executionStartIdx || 0;
  6217. var argsArrayLen = argsArray.length;
  6218. // Sometimes the OperatorList to execute is empty.
  6219. if (argsArrayLen === i) {
  6220. return i;
  6221. }
  6222. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6223. typeof continueCallback === 'function');
  6224. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6225. var steps = 0;
  6226. var commonObjs = this.commonObjs;
  6227. var objs = this.objs;
  6228. var fnId;
  6229. while (true) {
  6230. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6231. stepper.breakIt(i, continueCallback);
  6232. return i;
  6233. }
  6234. fnId = fnArray[i];
  6235. if (fnId !== OPS.dependency) {
  6236. this[fnId].apply(this, argsArray[i]);
  6237. } else {
  6238. var deps = argsArray[i];
  6239. for (var n = 0, nn = deps.length; n < nn; n++) {
  6240. var depObjId = deps[n];
  6241. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6242. var objsPool = common ? commonObjs : objs;
  6243. // If the promise isn't resolved yet, add the continueCallback
  6244. // to the promise and bail out.
  6245. if (!objsPool.isResolved(depObjId)) {
  6246. objsPool.get(depObjId, continueCallback);
  6247. return i;
  6248. }
  6249. }
  6250. }
  6251. i++;
  6252. // If the entire operatorList was executed, stop as were done.
  6253. if (i === argsArrayLen) {
  6254. return i;
  6255. }
  6256. // If the execution took longer then a certain amount of time and
  6257. // `continueCallback` is specified, interrupt the execution.
  6258. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6259. if (Date.now() > endTime) {
  6260. continueCallback();
  6261. return i;
  6262. }
  6263. steps = 0;
  6264. }
  6265. // If the operatorList isn't executed completely yet OR the execution
  6266. // time was short enough, do another execution round.
  6267. }
  6268. },
  6269. endDrawing: function CanvasGraphics_endDrawing() {
  6270. this.ctx.restore();
  6271. if (this.transparentCanvas) {
  6272. this.ctx = this.compositeCtx;
  6273. this.ctx.save();
  6274. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6275. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6276. this.ctx.restore();
  6277. this.transparentCanvas = null;
  6278. }
  6279. this.cachedCanvases.clear();
  6280. WebGLUtils.clear();
  6281. if (this.imageLayer) {
  6282. this.imageLayer.endLayout();
  6283. }
  6284. },
  6285. // Graphics state
  6286. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6287. this.current.lineWidth = width;
  6288. this.ctx.lineWidth = width;
  6289. },
  6290. setLineCap: function CanvasGraphics_setLineCap(style) {
  6291. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6292. },
  6293. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6294. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6295. },
  6296. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6297. this.ctx.miterLimit = limit;
  6298. },
  6299. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6300. var ctx = this.ctx;
  6301. if (ctx.setLineDash !== undefined) {
  6302. ctx.setLineDash(dashArray);
  6303. ctx.lineDashOffset = dashPhase;
  6304. } else {
  6305. ctx.mozDash = dashArray;
  6306. ctx.mozDashOffset = dashPhase;
  6307. }
  6308. },
  6309. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6310. // Maybe if we one day fully support color spaces this will be important
  6311. // for now we can ignore.
  6312. // TODO set rendering intent?
  6313. },
  6314. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6315. // There's no way to control this with canvas, but we can safely ignore.
  6316. // TODO set flatness?
  6317. },
  6318. setGState: function CanvasGraphics_setGState(states) {
  6319. for (var i = 0, ii = states.length; i < ii; i++) {
  6320. var state = states[i];
  6321. var key = state[0];
  6322. var value = state[1];
  6323. switch (key) {
  6324. case 'LW':
  6325. this.setLineWidth(value);
  6326. break;
  6327. case 'LC':
  6328. this.setLineCap(value);
  6329. break;
  6330. case 'LJ':
  6331. this.setLineJoin(value);
  6332. break;
  6333. case 'ML':
  6334. this.setMiterLimit(value);
  6335. break;
  6336. case 'D':
  6337. this.setDash(value[0], value[1]);
  6338. break;
  6339. case 'RI':
  6340. this.setRenderingIntent(value);
  6341. break;
  6342. case 'FL':
  6343. this.setFlatness(value);
  6344. break;
  6345. case 'Font':
  6346. this.setFont(value[0], value[1]);
  6347. break;
  6348. case 'CA':
  6349. this.current.strokeAlpha = state[1];
  6350. break;
  6351. case 'ca':
  6352. this.current.fillAlpha = state[1];
  6353. this.ctx.globalAlpha = state[1];
  6354. break;
  6355. case 'BM':
  6356. if (value && value.name && (value.name !== 'Normal')) {
  6357. var mode = value.name.replace(/([A-Z])/g,
  6358. function(c) {
  6359. return '-' + c.toLowerCase();
  6360. }
  6361. ).substring(1);
  6362. this.ctx.globalCompositeOperation = mode;
  6363. if (this.ctx.globalCompositeOperation !== mode) {
  6364. warn('globalCompositeOperation "' + mode +
  6365. '" is not supported');
  6366. }
  6367. } else {
  6368. this.ctx.globalCompositeOperation = 'source-over';
  6369. }
  6370. break;
  6371. case 'SMask':
  6372. if (this.current.activeSMask) {
  6373. this.endSMaskGroup();
  6374. }
  6375. this.current.activeSMask = value ? this.tempSMask : null;
  6376. if (this.current.activeSMask) {
  6377. this.beginSMaskGroup();
  6378. }
  6379. this.tempSMask = null;
  6380. break;
  6381. }
  6382. }
  6383. },
  6384. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6385. var activeSMask = this.current.activeSMask;
  6386. var drawnWidth = activeSMask.canvas.width;
  6387. var drawnHeight = activeSMask.canvas.height;
  6388. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6389. var scratchCanvas = this.cachedCanvases.getCanvas(
  6390. cacheId, drawnWidth, drawnHeight, true);
  6391. var currentCtx = this.ctx;
  6392. var currentTransform = currentCtx.mozCurrentTransform;
  6393. this.ctx.save();
  6394. var groupCtx = scratchCanvas.context;
  6395. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6396. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6397. groupCtx.transform.apply(groupCtx, currentTransform);
  6398. copyCtxState(currentCtx, groupCtx);
  6399. this.ctx = groupCtx;
  6400. this.setGState([
  6401. ['BM', 'Normal'],
  6402. ['ca', 1],
  6403. ['CA', 1]
  6404. ]);
  6405. this.groupStack.push(currentCtx);
  6406. this.groupLevel++;
  6407. },
  6408. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6409. var groupCtx = this.ctx;
  6410. this.groupLevel--;
  6411. this.ctx = this.groupStack.pop();
  6412. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6413. this.ctx.restore();
  6414. copyCtxState(groupCtx, this.ctx);
  6415. },
  6416. save: function CanvasGraphics_save() {
  6417. this.ctx.save();
  6418. var old = this.current;
  6419. this.stateStack.push(old);
  6420. this.current = old.clone();
  6421. this.current.activeSMask = null;
  6422. },
  6423. restore: function CanvasGraphics_restore() {
  6424. if (this.stateStack.length !== 0) {
  6425. if (this.current.activeSMask !== null) {
  6426. this.endSMaskGroup();
  6427. }
  6428. this.current = this.stateStack.pop();
  6429. this.ctx.restore();
  6430. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  6431. this.pendingClip = null;
  6432. this.cachedGetSinglePixelWidth = null;
  6433. }
  6434. },
  6435. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  6436. this.ctx.transform(a, b, c, d, e, f);
  6437. this.cachedGetSinglePixelWidth = null;
  6438. },
  6439. // Path
  6440. constructPath: function CanvasGraphics_constructPath(ops, args) {
  6441. var ctx = this.ctx;
  6442. var current = this.current;
  6443. var x = current.x, y = current.y;
  6444. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6445. switch (ops[i] | 0) {
  6446. case OPS.rectangle:
  6447. x = args[j++];
  6448. y = args[j++];
  6449. var width = args[j++];
  6450. var height = args[j++];
  6451. if (width === 0) {
  6452. width = this.getSinglePixelWidth();
  6453. }
  6454. if (height === 0) {
  6455. height = this.getSinglePixelWidth();
  6456. }
  6457. var xw = x + width;
  6458. var yh = y + height;
  6459. this.ctx.moveTo(x, y);
  6460. this.ctx.lineTo(xw, y);
  6461. this.ctx.lineTo(xw, yh);
  6462. this.ctx.lineTo(x, yh);
  6463. this.ctx.lineTo(x, y);
  6464. this.ctx.closePath();
  6465. break;
  6466. case OPS.moveTo:
  6467. x = args[j++];
  6468. y = args[j++];
  6469. ctx.moveTo(x, y);
  6470. break;
  6471. case OPS.lineTo:
  6472. x = args[j++];
  6473. y = args[j++];
  6474. ctx.lineTo(x, y);
  6475. break;
  6476. case OPS.curveTo:
  6477. x = args[j + 4];
  6478. y = args[j + 5];
  6479. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  6480. x, y);
  6481. j += 6;
  6482. break;
  6483. case OPS.curveTo2:
  6484. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  6485. args[j + 2], args[j + 3]);
  6486. x = args[j + 2];
  6487. y = args[j + 3];
  6488. j += 4;
  6489. break;
  6490. case OPS.curveTo3:
  6491. x = args[j + 2];
  6492. y = args[j + 3];
  6493. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6494. j += 4;
  6495. break;
  6496. case OPS.closePath:
  6497. ctx.closePath();
  6498. break;
  6499. }
  6500. }
  6501. current.setCurrentPoint(x, y);
  6502. },
  6503. closePath: function CanvasGraphics_closePath() {
  6504. this.ctx.closePath();
  6505. },
  6506. stroke: function CanvasGraphics_stroke(consumePath) {
  6507. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  6508. var ctx = this.ctx;
  6509. var strokeColor = this.current.strokeColor;
  6510. // Prevent drawing too thin lines by enforcing a minimum line width.
  6511. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  6512. this.current.lineWidth);
  6513. // For stroke we want to temporarily change the global alpha to the
  6514. // stroking alpha.
  6515. ctx.globalAlpha = this.current.strokeAlpha;
  6516. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  6517. strokeColor.type === 'Pattern') {
  6518. // for patterns, we transform to pattern space, calculate
  6519. // the pattern, call stroke, and restore to user space
  6520. ctx.save();
  6521. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  6522. ctx.stroke();
  6523. ctx.restore();
  6524. } else {
  6525. ctx.stroke();
  6526. }
  6527. if (consumePath) {
  6528. this.consumePath();
  6529. }
  6530. // Restore the global alpha to the fill alpha
  6531. ctx.globalAlpha = this.current.fillAlpha;
  6532. },
  6533. closeStroke: function CanvasGraphics_closeStroke() {
  6534. this.closePath();
  6535. this.stroke();
  6536. },
  6537. fill: function CanvasGraphics_fill(consumePath) {
  6538. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  6539. var ctx = this.ctx;
  6540. var fillColor = this.current.fillColor;
  6541. var isPatternFill = this.current.patternFill;
  6542. var needRestore = false;
  6543. if (isPatternFill) {
  6544. ctx.save();
  6545. if (this.baseTransform) {
  6546. ctx.setTransform.apply(ctx, this.baseTransform);
  6547. }
  6548. ctx.fillStyle = fillColor.getPattern(ctx, this);
  6549. needRestore = true;
  6550. }
  6551. if (this.pendingEOFill) {
  6552. if (ctx.mozFillRule !== undefined) {
  6553. ctx.mozFillRule = 'evenodd';
  6554. ctx.fill();
  6555. ctx.mozFillRule = 'nonzero';
  6556. } else {
  6557. ctx.fill('evenodd');
  6558. }
  6559. this.pendingEOFill = false;
  6560. } else {
  6561. ctx.fill();
  6562. }
  6563. if (needRestore) {
  6564. ctx.restore();
  6565. }
  6566. if (consumePath) {
  6567. this.consumePath();
  6568. }
  6569. },
  6570. eoFill: function CanvasGraphics_eoFill() {
  6571. this.pendingEOFill = true;
  6572. this.fill();
  6573. },
  6574. fillStroke: function CanvasGraphics_fillStroke() {
  6575. this.fill(false);
  6576. this.stroke(false);
  6577. this.consumePath();
  6578. },
  6579. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  6580. this.pendingEOFill = true;
  6581. this.fillStroke();
  6582. },
  6583. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  6584. this.closePath();
  6585. this.fillStroke();
  6586. },
  6587. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  6588. this.pendingEOFill = true;
  6589. this.closePath();
  6590. this.fillStroke();
  6591. },
  6592. endPath: function CanvasGraphics_endPath() {
  6593. this.consumePath();
  6594. },
  6595. // Clipping
  6596. clip: function CanvasGraphics_clip() {
  6597. this.pendingClip = NORMAL_CLIP;
  6598. },
  6599. eoClip: function CanvasGraphics_eoClip() {
  6600. this.pendingClip = EO_CLIP;
  6601. },
  6602. // Text
  6603. beginText: function CanvasGraphics_beginText() {
  6604. this.current.textMatrix = IDENTITY_MATRIX;
  6605. this.current.textMatrixScale = 1;
  6606. this.current.x = this.current.lineX = 0;
  6607. this.current.y = this.current.lineY = 0;
  6608. },
  6609. endText: function CanvasGraphics_endText() {
  6610. var paths = this.pendingTextPaths;
  6611. var ctx = this.ctx;
  6612. if (paths === undefined) {
  6613. ctx.beginPath();
  6614. return;
  6615. }
  6616. ctx.save();
  6617. ctx.beginPath();
  6618. for (var i = 0; i < paths.length; i++) {
  6619. var path = paths[i];
  6620. ctx.setTransform.apply(ctx, path.transform);
  6621. ctx.translate(path.x, path.y);
  6622. path.addToPath(ctx, path.fontSize);
  6623. }
  6624. ctx.restore();
  6625. ctx.clip();
  6626. ctx.beginPath();
  6627. delete this.pendingTextPaths;
  6628. },
  6629. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  6630. this.current.charSpacing = spacing;
  6631. },
  6632. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  6633. this.current.wordSpacing = spacing;
  6634. },
  6635. setHScale: function CanvasGraphics_setHScale(scale) {
  6636. this.current.textHScale = scale / 100;
  6637. },
  6638. setLeading: function CanvasGraphics_setLeading(leading) {
  6639. this.current.leading = -leading;
  6640. },
  6641. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  6642. var fontObj = this.commonObjs.get(fontRefName);
  6643. var current = this.current;
  6644. if (!fontObj) {
  6645. error('Can\'t find font for ' + fontRefName);
  6646. }
  6647. current.fontMatrix = (fontObj.fontMatrix ?
  6648. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6649. // A valid matrix needs all main diagonal elements to be non-zero
  6650. // This also ensures we bypass FF bugzilla bug #719844.
  6651. if (current.fontMatrix[0] === 0 ||
  6652. current.fontMatrix[3] === 0) {
  6653. warn('Invalid font matrix for font ' + fontRefName);
  6654. }
  6655. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  6656. // and in some docs this can be negative (inverted x-y axes).
  6657. if (size < 0) {
  6658. size = -size;
  6659. current.fontDirection = -1;
  6660. } else {
  6661. current.fontDirection = 1;
  6662. }
  6663. this.current.font = fontObj;
  6664. this.current.fontSize = size;
  6665. if (fontObj.isType3Font) {
  6666. return; // we don't need ctx.font for Type3 fonts
  6667. }
  6668. var name = fontObj.loadedName || 'sans-serif';
  6669. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  6670. (fontObj.bold ? 'bold' : 'normal');
  6671. var italic = fontObj.italic ? 'italic' : 'normal';
  6672. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  6673. // Some font backends cannot handle fonts below certain size.
  6674. // Keeping the font at minimal size and using the fontSizeScale to change
  6675. // the current transformation matrix before the fillText/strokeText.
  6676. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  6677. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  6678. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  6679. this.current.fontSizeScale = size / browserFontSize;
  6680. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  6681. this.ctx.font = rule;
  6682. },
  6683. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  6684. this.current.textRenderingMode = mode;
  6685. },
  6686. setTextRise: function CanvasGraphics_setTextRise(rise) {
  6687. this.current.textRise = rise;
  6688. },
  6689. moveText: function CanvasGraphics_moveText(x, y) {
  6690. this.current.x = this.current.lineX += x;
  6691. this.current.y = this.current.lineY += y;
  6692. },
  6693. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  6694. this.setLeading(-y);
  6695. this.moveText(x, y);
  6696. },
  6697. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  6698. this.current.textMatrix = [a, b, c, d, e, f];
  6699. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  6700. this.current.x = this.current.lineX = 0;
  6701. this.current.y = this.current.lineY = 0;
  6702. },
  6703. nextLine: function CanvasGraphics_nextLine() {
  6704. this.moveText(0, this.current.leading);
  6705. },
  6706. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  6707. var ctx = this.ctx;
  6708. var current = this.current;
  6709. var font = current.font;
  6710. var textRenderingMode = current.textRenderingMode;
  6711. var fontSize = current.fontSize / current.fontSizeScale;
  6712. var fillStrokeMode = textRenderingMode &
  6713. TextRenderingMode.FILL_STROKE_MASK;
  6714. var isAddToPathSet = !!(textRenderingMode &
  6715. TextRenderingMode.ADD_TO_PATH_FLAG);
  6716. var addToPath;
  6717. if (font.disableFontFace || isAddToPathSet) {
  6718. addToPath = font.getPathGenerator(this.commonObjs, character);
  6719. }
  6720. if (font.disableFontFace) {
  6721. ctx.save();
  6722. ctx.translate(x, y);
  6723. ctx.beginPath();
  6724. addToPath(ctx, fontSize);
  6725. if (fillStrokeMode === TextRenderingMode.FILL ||
  6726. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6727. ctx.fill();
  6728. }
  6729. if (fillStrokeMode === TextRenderingMode.STROKE ||
  6730. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6731. ctx.stroke();
  6732. }
  6733. ctx.restore();
  6734. } else {
  6735. if (fillStrokeMode === TextRenderingMode.FILL ||
  6736. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6737. ctx.fillText(character, x, y);
  6738. }
  6739. if (fillStrokeMode === TextRenderingMode.STROKE ||
  6740. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6741. ctx.strokeText(character, x, y);
  6742. }
  6743. }
  6744. if (isAddToPathSet) {
  6745. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6746. paths.push({
  6747. transform: ctx.mozCurrentTransform,
  6748. x: x,
  6749. y: y,
  6750. fontSize: fontSize,
  6751. addToPath: addToPath
  6752. });
  6753. }
  6754. },
  6755. get isFontSubpixelAAEnabled() {
  6756. // Checks if anti-aliasing is enabled when scaled text is painted.
  6757. // On Windows GDI scaled fonts looks bad.
  6758. var ctx = document.createElement('canvas').getContext('2d');
  6759. ctx.scale(1.5, 1);
  6760. ctx.fillText('I', 0, 10);
  6761. var data = ctx.getImageData(0, 0, 10, 10).data;
  6762. var enabled = false;
  6763. for (var i = 3; i < data.length; i += 4) {
  6764. if (data[i] > 0 && data[i] < 255) {
  6765. enabled = true;
  6766. break;
  6767. }
  6768. }
  6769. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  6770. },
  6771. showText: function CanvasGraphics_showText(glyphs) {
  6772. var current = this.current;
  6773. var font = current.font;
  6774. if (font.isType3Font) {
  6775. return this.showType3Text(glyphs);
  6776. }
  6777. var fontSize = current.fontSize;
  6778. if (fontSize === 0) {
  6779. return;
  6780. }
  6781. var ctx = this.ctx;
  6782. var fontSizeScale = current.fontSizeScale;
  6783. var charSpacing = current.charSpacing;
  6784. var wordSpacing = current.wordSpacing;
  6785. var fontDirection = current.fontDirection;
  6786. var textHScale = current.textHScale * fontDirection;
  6787. var glyphsLength = glyphs.length;
  6788. var vertical = font.vertical;
  6789. var spacingDir = vertical ? 1 : -1;
  6790. var defaultVMetrics = font.defaultVMetrics;
  6791. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6792. var simpleFillText =
  6793. current.textRenderingMode === TextRenderingMode.FILL &&
  6794. !font.disableFontFace;
  6795. ctx.save();
  6796. ctx.transform.apply(ctx, current.textMatrix);
  6797. ctx.translate(current.x, current.y + current.textRise);
  6798. if (current.patternFill) {
  6799. // TODO: Some shading patterns are not applied correctly to text,
  6800. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  6801. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  6802. }
  6803. if (fontDirection > 0) {
  6804. ctx.scale(textHScale, -1);
  6805. } else {
  6806. ctx.scale(textHScale, 1);
  6807. }
  6808. var lineWidth = current.lineWidth;
  6809. var scale = current.textMatrixScale;
  6810. if (scale === 0 || lineWidth === 0) {
  6811. var fillStrokeMode = current.textRenderingMode &
  6812. TextRenderingMode.FILL_STROKE_MASK;
  6813. if (fillStrokeMode === TextRenderingMode.STROKE ||
  6814. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6815. this.cachedGetSinglePixelWidth = null;
  6816. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  6817. }
  6818. } else {
  6819. lineWidth /= scale;
  6820. }
  6821. if (fontSizeScale !== 1.0) {
  6822. ctx.scale(fontSizeScale, fontSizeScale);
  6823. lineWidth /= fontSizeScale;
  6824. }
  6825. ctx.lineWidth = lineWidth;
  6826. var x = 0, i;
  6827. for (i = 0; i < glyphsLength; ++i) {
  6828. var glyph = glyphs[i];
  6829. if (isNum(glyph)) {
  6830. x += spacingDir * glyph * fontSize / 1000;
  6831. continue;
  6832. }
  6833. var restoreNeeded = false;
  6834. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6835. var character = glyph.fontChar;
  6836. var accent = glyph.accent;
  6837. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  6838. var width = glyph.width;
  6839. if (vertical) {
  6840. var vmetric, vx, vy;
  6841. vmetric = glyph.vmetric || defaultVMetrics;
  6842. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  6843. vx = -vx * widthAdvanceScale;
  6844. vy = vmetric[2] * widthAdvanceScale;
  6845. width = vmetric ? -vmetric[0] : width;
  6846. scaledX = vx / fontSizeScale;
  6847. scaledY = (x + vy) / fontSizeScale;
  6848. } else {
  6849. scaledX = x / fontSizeScale;
  6850. scaledY = 0;
  6851. }
  6852. if (font.remeasure && width > 0) {
  6853. // Some standard fonts may not have the exact width: rescale per
  6854. // character if measured width is greater than expected glyph width
  6855. // and subpixel-aa is enabled, otherwise just center the glyph.
  6856. var measuredWidth = ctx.measureText(character).width * 1000 /
  6857. fontSize * fontSizeScale;
  6858. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6859. var characterScaleX = width / measuredWidth;
  6860. restoreNeeded = true;
  6861. ctx.save();
  6862. ctx.scale(characterScaleX, 1);
  6863. scaledX /= characterScaleX;
  6864. } else if (width !== measuredWidth) {
  6865. scaledX += (width - measuredWidth) / 2000 *
  6866. fontSize / fontSizeScale;
  6867. }
  6868. }
  6869. // Only attempt to draw the glyph if it is actually in the embedded font
  6870. // file or if there isn't a font file so the fallback font is shown.
  6871. if (glyph.isInFont || font.missingFile) {
  6872. if (simpleFillText && !accent) {
  6873. // common case
  6874. ctx.fillText(character, scaledX, scaledY);
  6875. } else {
  6876. this.paintChar(character, scaledX, scaledY);
  6877. if (accent) {
  6878. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  6879. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  6880. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  6881. }
  6882. }
  6883. }
  6884. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6885. x += charWidth;
  6886. if (restoreNeeded) {
  6887. ctx.restore();
  6888. }
  6889. }
  6890. if (vertical) {
  6891. current.y -= x * textHScale;
  6892. } else {
  6893. current.x += x * textHScale;
  6894. }
  6895. ctx.restore();
  6896. },
  6897. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  6898. // Type3 fonts - each glyph is a "mini-PDF"
  6899. var ctx = this.ctx;
  6900. var current = this.current;
  6901. var font = current.font;
  6902. var fontSize = current.fontSize;
  6903. var fontDirection = current.fontDirection;
  6904. var spacingDir = font.vertical ? 1 : -1;
  6905. var charSpacing = current.charSpacing;
  6906. var wordSpacing = current.wordSpacing;
  6907. var textHScale = current.textHScale * fontDirection;
  6908. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  6909. var glyphsLength = glyphs.length;
  6910. var isTextInvisible =
  6911. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  6912. var i, glyph, width, spacingLength;
  6913. if (isTextInvisible || fontSize === 0) {
  6914. return;
  6915. }
  6916. this.cachedGetSinglePixelWidth = null;
  6917. ctx.save();
  6918. ctx.transform.apply(ctx, current.textMatrix);
  6919. ctx.translate(current.x, current.y);
  6920. ctx.scale(textHScale, fontDirection);
  6921. for (i = 0; i < glyphsLength; ++i) {
  6922. glyph = glyphs[i];
  6923. if (isNum(glyph)) {
  6924. spacingLength = spacingDir * glyph * fontSize / 1000;
  6925. this.ctx.translate(spacingLength, 0);
  6926. current.x += spacingLength * textHScale;
  6927. continue;
  6928. }
  6929. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6930. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  6931. if (!operatorList) {
  6932. warn('Type3 character \"' + glyph.operatorListId +
  6933. '\" is not available');
  6934. continue;
  6935. }
  6936. this.processingType3 = glyph;
  6937. this.save();
  6938. ctx.scale(fontSize, fontSize);
  6939. ctx.transform.apply(ctx, fontMatrix);
  6940. this.executeOperatorList(operatorList);
  6941. this.restore();
  6942. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  6943. width = transformed[0] * fontSize + spacing;
  6944. ctx.translate(width, 0);
  6945. current.x += width * textHScale;
  6946. }
  6947. ctx.restore();
  6948. this.processingType3 = null;
  6949. },
  6950. // Type3 fonts
  6951. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  6952. // We can safely ignore this since the width should be the same
  6953. // as the width in the Widths array.
  6954. },
  6955. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  6956. yWidth,
  6957. llx,
  6958. lly,
  6959. urx,
  6960. ury) {
  6961. // TODO According to the spec we're also suppose to ignore any operators
  6962. // that set color or include images while processing this type3 font.
  6963. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6964. this.clip();
  6965. this.endPath();
  6966. },
  6967. // Color
  6968. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  6969. var pattern;
  6970. if (IR[0] === 'TilingPattern') {
  6971. var color = IR[1];
  6972. var baseTransform = this.baseTransform ||
  6973. this.ctx.mozCurrentTransform.slice();
  6974. var self = this;
  6975. var canvasGraphicsFactory = {
  6976. createCanvasGraphics: function (ctx) {
  6977. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  6978. }
  6979. };
  6980. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  6981. baseTransform);
  6982. } else {
  6983. pattern = getShadingPatternFromIR(IR);
  6984. }
  6985. return pattern;
  6986. },
  6987. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  6988. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6989. },
  6990. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  6991. this.current.fillColor = this.getColorN_Pattern(arguments);
  6992. this.current.patternFill = true;
  6993. },
  6994. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  6995. var color = Util.makeCssRgb(r, g, b);
  6996. this.ctx.strokeStyle = color;
  6997. this.current.strokeColor = color;
  6998. },
  6999. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7000. var color = Util.makeCssRgb(r, g, b);
  7001. this.ctx.fillStyle = color;
  7002. this.current.fillColor = color;
  7003. this.current.patternFill = false;
  7004. },
  7005. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7006. var ctx = this.ctx;
  7007. this.save();
  7008. var pattern = getShadingPatternFromIR(patternIR);
  7009. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7010. var inv = ctx.mozCurrentTransformInverse;
  7011. if (inv) {
  7012. var canvas = ctx.canvas;
  7013. var width = canvas.width;
  7014. var height = canvas.height;
  7015. var bl = Util.applyTransform([0, 0], inv);
  7016. var br = Util.applyTransform([0, height], inv);
  7017. var ul = Util.applyTransform([width, 0], inv);
  7018. var ur = Util.applyTransform([width, height], inv);
  7019. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7020. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7021. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7022. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7023. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7024. } else {
  7025. // HACK to draw the gradient onto an infinite rectangle.
  7026. // PDF gradients are drawn across the entire image while
  7027. // Canvas only allows gradients to be drawn in a rectangle
  7028. // The following bug should allow us to remove this.
  7029. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7030. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7031. }
  7032. this.restore();
  7033. },
  7034. // Images
  7035. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7036. error('Should not call beginInlineImage');
  7037. },
  7038. beginImageData: function CanvasGraphics_beginImageData() {
  7039. error('Should not call beginImageData');
  7040. },
  7041. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7042. bbox) {
  7043. this.save();
  7044. this.baseTransformStack.push(this.baseTransform);
  7045. if (isArray(matrix) && 6 === matrix.length) {
  7046. this.transform.apply(this, matrix);
  7047. }
  7048. this.baseTransform = this.ctx.mozCurrentTransform;
  7049. if (isArray(bbox) && 4 === bbox.length) {
  7050. var width = bbox[2] - bbox[0];
  7051. var height = bbox[3] - bbox[1];
  7052. this.ctx.rect(bbox[0], bbox[1], width, height);
  7053. this.clip();
  7054. this.endPath();
  7055. }
  7056. },
  7057. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7058. this.restore();
  7059. this.baseTransform = this.baseTransformStack.pop();
  7060. },
  7061. beginGroup: function CanvasGraphics_beginGroup(group) {
  7062. this.save();
  7063. var currentCtx = this.ctx;
  7064. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7065. // group results aren't usually that different and they even have tools
  7066. // that ignore this setting. Notes from Rik on implmenting:
  7067. // - When you encounter an transparency group, create a new canvas with
  7068. // the dimensions of the bbox
  7069. // - copy the content from the previous canvas to the new canvas
  7070. // - draw as usual
  7071. // - remove the backdrop alpha:
  7072. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7073. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7074. // backdrop
  7075. // - remove background color:
  7076. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7077. if (!group.isolated) {
  7078. info('TODO: Support non-isolated groups.');
  7079. }
  7080. // TODO knockout - supposedly possible with the clever use of compositing
  7081. // modes.
  7082. if (group.knockout) {
  7083. warn('Knockout groups not supported.');
  7084. }
  7085. var currentTransform = currentCtx.mozCurrentTransform;
  7086. if (group.matrix) {
  7087. currentCtx.transform.apply(currentCtx, group.matrix);
  7088. }
  7089. assert(group.bbox, 'Bounding box is required.');
  7090. // Based on the current transform figure out how big the bounding box
  7091. // will actually be.
  7092. var bounds = Util.getAxialAlignedBoundingBox(
  7093. group.bbox,
  7094. currentCtx.mozCurrentTransform);
  7095. // Clip the bounding box to the current canvas.
  7096. var canvasBounds = [0,
  7097. 0,
  7098. currentCtx.canvas.width,
  7099. currentCtx.canvas.height];
  7100. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7101. // Use ceil in case we're between sizes so we don't create canvas that is
  7102. // too small and make the canvas at least 1x1 pixels.
  7103. var offsetX = Math.floor(bounds[0]);
  7104. var offsetY = Math.floor(bounds[1]);
  7105. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7106. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7107. var scaleX = 1, scaleY = 1;
  7108. if (drawnWidth > MAX_GROUP_SIZE) {
  7109. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7110. drawnWidth = MAX_GROUP_SIZE;
  7111. }
  7112. if (drawnHeight > MAX_GROUP_SIZE) {
  7113. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7114. drawnHeight = MAX_GROUP_SIZE;
  7115. }
  7116. var cacheId = 'groupAt' + this.groupLevel;
  7117. if (group.smask) {
  7118. // Using two cache entries is case if masks are used one after another.
  7119. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7120. }
  7121. var scratchCanvas = this.cachedCanvases.getCanvas(
  7122. cacheId, drawnWidth, drawnHeight, true);
  7123. var groupCtx = scratchCanvas.context;
  7124. // Since we created a new canvas that is just the size of the bounding box
  7125. // we have to translate the group ctx.
  7126. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7127. groupCtx.translate(-offsetX, -offsetY);
  7128. groupCtx.transform.apply(groupCtx, currentTransform);
  7129. if (group.smask) {
  7130. // Saving state and cached mask to be used in setGState.
  7131. this.smaskStack.push({
  7132. canvas: scratchCanvas.canvas,
  7133. context: groupCtx,
  7134. offsetX: offsetX,
  7135. offsetY: offsetY,
  7136. scaleX: scaleX,
  7137. scaleY: scaleY,
  7138. subtype: group.smask.subtype,
  7139. backdrop: group.smask.backdrop,
  7140. transferMap: group.smask.transferMap || null
  7141. });
  7142. } else {
  7143. // Setup the current ctx so when the group is popped we draw it at the
  7144. // right location.
  7145. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7146. currentCtx.translate(offsetX, offsetY);
  7147. currentCtx.scale(scaleX, scaleY);
  7148. }
  7149. // The transparency group inherits all off the current graphics state
  7150. // except the blend mode, soft mask, and alpha constants.
  7151. copyCtxState(currentCtx, groupCtx);
  7152. this.ctx = groupCtx;
  7153. this.setGState([
  7154. ['BM', 'Normal'],
  7155. ['ca', 1],
  7156. ['CA', 1]
  7157. ]);
  7158. this.groupStack.push(currentCtx);
  7159. this.groupLevel++;
  7160. },
  7161. endGroup: function CanvasGraphics_endGroup(group) {
  7162. this.groupLevel--;
  7163. var groupCtx = this.ctx;
  7164. this.ctx = this.groupStack.pop();
  7165. // Turn off image smoothing to avoid sub pixel interpolation which can
  7166. // look kind of blurry for some pdfs.
  7167. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7168. this.ctx.imageSmoothingEnabled = false;
  7169. } else {
  7170. this.ctx.mozImageSmoothingEnabled = false;
  7171. }
  7172. if (group.smask) {
  7173. this.tempSMask = this.smaskStack.pop();
  7174. } else {
  7175. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7176. }
  7177. this.restore();
  7178. },
  7179. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7180. this.save();
  7181. this.current = new CanvasExtraState();
  7182. if (this.baseTransform) {
  7183. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7184. }
  7185. },
  7186. endAnnotations: function CanvasGraphics_endAnnotations() {
  7187. this.restore();
  7188. },
  7189. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7190. matrix) {
  7191. this.save();
  7192. if (isArray(rect) && 4 === rect.length) {
  7193. var width = rect[2] - rect[0];
  7194. var height = rect[3] - rect[1];
  7195. this.ctx.rect(rect[0], rect[1], width, height);
  7196. this.clip();
  7197. this.endPath();
  7198. }
  7199. this.transform.apply(this, transform);
  7200. this.transform.apply(this, matrix);
  7201. },
  7202. endAnnotation: function CanvasGraphics_endAnnotation() {
  7203. this.restore();
  7204. },
  7205. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7206. var domImage = this.objs.get(objId);
  7207. if (!domImage) {
  7208. warn('Dependent image isn\'t ready yet');
  7209. return;
  7210. }
  7211. this.save();
  7212. var ctx = this.ctx;
  7213. // scale the image to the unit square
  7214. ctx.scale(1 / w, -1 / h);
  7215. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7216. 0, -h, w, h);
  7217. if (this.imageLayer) {
  7218. var currentTransform = ctx.mozCurrentTransformInverse;
  7219. var position = this.getCanvasPosition(0, 0);
  7220. this.imageLayer.appendImage({
  7221. objId: objId,
  7222. left: position[0],
  7223. top: position[1],
  7224. width: w / currentTransform[0],
  7225. height: h / currentTransform[3]
  7226. });
  7227. }
  7228. this.restore();
  7229. },
  7230. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7231. var ctx = this.ctx;
  7232. var width = img.width, height = img.height;
  7233. var fillColor = this.current.fillColor;
  7234. var isPatternFill = this.current.patternFill;
  7235. var glyph = this.processingType3;
  7236. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7237. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7238. glyph.compiled =
  7239. compileType3Glyph({data: img.data, width: width, height: height});
  7240. } else {
  7241. glyph.compiled = null;
  7242. }
  7243. }
  7244. if (glyph && glyph.compiled) {
  7245. glyph.compiled(ctx);
  7246. return;
  7247. }
  7248. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7249. width, height);
  7250. var maskCtx = maskCanvas.context;
  7251. maskCtx.save();
  7252. putBinaryImageMask(maskCtx, img);
  7253. maskCtx.globalCompositeOperation = 'source-in';
  7254. maskCtx.fillStyle = isPatternFill ?
  7255. fillColor.getPattern(maskCtx, this) : fillColor;
  7256. maskCtx.fillRect(0, 0, width, height);
  7257. maskCtx.restore();
  7258. this.paintInlineImageXObject(maskCanvas.canvas);
  7259. },
  7260. paintImageMaskXObjectRepeat:
  7261. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7262. scaleY, positions) {
  7263. var width = imgData.width;
  7264. var height = imgData.height;
  7265. var fillColor = this.current.fillColor;
  7266. var isPatternFill = this.current.patternFill;
  7267. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7268. width, height);
  7269. var maskCtx = maskCanvas.context;
  7270. maskCtx.save();
  7271. putBinaryImageMask(maskCtx, imgData);
  7272. maskCtx.globalCompositeOperation = 'source-in';
  7273. maskCtx.fillStyle = isPatternFill ?
  7274. fillColor.getPattern(maskCtx, this) : fillColor;
  7275. maskCtx.fillRect(0, 0, width, height);
  7276. maskCtx.restore();
  7277. var ctx = this.ctx;
  7278. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7279. ctx.save();
  7280. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7281. ctx.scale(1, -1);
  7282. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7283. 0, -1, 1, 1);
  7284. ctx.restore();
  7285. }
  7286. },
  7287. paintImageMaskXObjectGroup:
  7288. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7289. var ctx = this.ctx;
  7290. var fillColor = this.current.fillColor;
  7291. var isPatternFill = this.current.patternFill;
  7292. for (var i = 0, ii = images.length; i < ii; i++) {
  7293. var image = images[i];
  7294. var width = image.width, height = image.height;
  7295. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7296. width, height);
  7297. var maskCtx = maskCanvas.context;
  7298. maskCtx.save();
  7299. putBinaryImageMask(maskCtx, image);
  7300. maskCtx.globalCompositeOperation = 'source-in';
  7301. maskCtx.fillStyle = isPatternFill ?
  7302. fillColor.getPattern(maskCtx, this) : fillColor;
  7303. maskCtx.fillRect(0, 0, width, height);
  7304. maskCtx.restore();
  7305. ctx.save();
  7306. ctx.transform.apply(ctx, image.transform);
  7307. ctx.scale(1, -1);
  7308. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7309. 0, -1, 1, 1);
  7310. ctx.restore();
  7311. }
  7312. },
  7313. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7314. var imgData = this.objs.get(objId);
  7315. if (!imgData) {
  7316. warn('Dependent image isn\'t ready yet');
  7317. return;
  7318. }
  7319. this.paintInlineImageXObject(imgData);
  7320. },
  7321. paintImageXObjectRepeat:
  7322. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7323. positions) {
  7324. var imgData = this.objs.get(objId);
  7325. if (!imgData) {
  7326. warn('Dependent image isn\'t ready yet');
  7327. return;
  7328. }
  7329. var width = imgData.width;
  7330. var height = imgData.height;
  7331. var map = [];
  7332. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7333. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7334. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7335. }
  7336. this.paintInlineImageXObjectGroup(imgData, map);
  7337. },
  7338. paintInlineImageXObject:
  7339. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7340. var width = imgData.width;
  7341. var height = imgData.height;
  7342. var ctx = this.ctx;
  7343. this.save();
  7344. // scale the image to the unit square
  7345. ctx.scale(1 / width, -1 / height);
  7346. var currentTransform = ctx.mozCurrentTransformInverse;
  7347. var a = currentTransform[0], b = currentTransform[1];
  7348. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7349. var c = currentTransform[2], d = currentTransform[3];
  7350. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7351. var imgToPaint, tmpCanvas;
  7352. // instanceof HTMLElement does not work in jsdom node.js module
  7353. if (imgData instanceof HTMLElement || !imgData.data) {
  7354. imgToPaint = imgData;
  7355. } else {
  7356. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  7357. width, height);
  7358. var tmpCtx = tmpCanvas.context;
  7359. putBinaryImageData(tmpCtx, imgData);
  7360. imgToPaint = tmpCanvas.canvas;
  7361. }
  7362. var paintWidth = width, paintHeight = height;
  7363. var tmpCanvasId = 'prescale1';
  7364. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  7365. // pixels during drawImage operation, painting on the temporary canvas(es)
  7366. // that are twice smaller in size
  7367. while ((widthScale > 2 && paintWidth > 1) ||
  7368. (heightScale > 2 && paintHeight > 1)) {
  7369. var newWidth = paintWidth, newHeight = paintHeight;
  7370. if (widthScale > 2 && paintWidth > 1) {
  7371. newWidth = Math.ceil(paintWidth / 2);
  7372. widthScale /= paintWidth / newWidth;
  7373. }
  7374. if (heightScale > 2 && paintHeight > 1) {
  7375. newHeight = Math.ceil(paintHeight / 2);
  7376. heightScale /= paintHeight / newHeight;
  7377. }
  7378. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  7379. newWidth, newHeight);
  7380. tmpCtx = tmpCanvas.context;
  7381. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7382. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7383. 0, 0, newWidth, newHeight);
  7384. imgToPaint = tmpCanvas.canvas;
  7385. paintWidth = newWidth;
  7386. paintHeight = newHeight;
  7387. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7388. }
  7389. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7390. 0, -height, width, height);
  7391. if (this.imageLayer) {
  7392. var position = this.getCanvasPosition(0, -height);
  7393. this.imageLayer.appendImage({
  7394. imgData: imgData,
  7395. left: position[0],
  7396. top: position[1],
  7397. width: width / currentTransform[0],
  7398. height: height / currentTransform[3]
  7399. });
  7400. }
  7401. this.restore();
  7402. },
  7403. paintInlineImageXObjectGroup:
  7404. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  7405. var ctx = this.ctx;
  7406. var w = imgData.width;
  7407. var h = imgData.height;
  7408. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  7409. var tmpCtx = tmpCanvas.context;
  7410. putBinaryImageData(tmpCtx, imgData);
  7411. for (var i = 0, ii = map.length; i < ii; i++) {
  7412. var entry = map[i];
  7413. ctx.save();
  7414. ctx.transform.apply(ctx, entry.transform);
  7415. ctx.scale(1, -1);
  7416. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  7417. 0, -1, 1, 1);
  7418. if (this.imageLayer) {
  7419. var position = this.getCanvasPosition(entry.x, entry.y);
  7420. this.imageLayer.appendImage({
  7421. imgData: imgData,
  7422. left: position[0],
  7423. top: position[1],
  7424. width: w,
  7425. height: h
  7426. });
  7427. }
  7428. ctx.restore();
  7429. }
  7430. },
  7431. paintSolidColorImageMask:
  7432. function CanvasGraphics_paintSolidColorImageMask() {
  7433. this.ctx.fillRect(0, 0, 1, 1);
  7434. },
  7435. paintXObject: function CanvasGraphics_paintXObject() {
  7436. warn('Unsupported \'paintXObject\' command.');
  7437. },
  7438. // Marked content
  7439. markPoint: function CanvasGraphics_markPoint(tag) {
  7440. // TODO Marked content.
  7441. },
  7442. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  7443. // TODO Marked content.
  7444. },
  7445. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  7446. // TODO Marked content.
  7447. },
  7448. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  7449. tag, properties) {
  7450. // TODO Marked content.
  7451. },
  7452. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  7453. // TODO Marked content.
  7454. },
  7455. // Compatibility
  7456. beginCompat: function CanvasGraphics_beginCompat() {
  7457. // TODO ignore undefined operators (should we do that anyway?)
  7458. },
  7459. endCompat: function CanvasGraphics_endCompat() {
  7460. // TODO stop ignoring undefined operators
  7461. },
  7462. // Helper functions
  7463. consumePath: function CanvasGraphics_consumePath() {
  7464. var ctx = this.ctx;
  7465. if (this.pendingClip) {
  7466. if (this.pendingClip === EO_CLIP) {
  7467. if (ctx.mozFillRule !== undefined) {
  7468. ctx.mozFillRule = 'evenodd';
  7469. ctx.clip();
  7470. ctx.mozFillRule = 'nonzero';
  7471. } else {
  7472. ctx.clip('evenodd');
  7473. }
  7474. } else {
  7475. ctx.clip();
  7476. }
  7477. this.pendingClip = null;
  7478. }
  7479. ctx.beginPath();
  7480. },
  7481. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  7482. if (this.cachedGetSinglePixelWidth === null) {
  7483. var inverse = this.ctx.mozCurrentTransformInverse;
  7484. // max of the current horizontal and vertical scale
  7485. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  7486. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  7487. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  7488. }
  7489. return this.cachedGetSinglePixelWidth;
  7490. },
  7491. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  7492. var transform = this.ctx.mozCurrentTransform;
  7493. return [
  7494. transform[0] * x + transform[2] * y + transform[4],
  7495. transform[1] * x + transform[3] * y + transform[5]
  7496. ];
  7497. }
  7498. };
  7499. for (var op in OPS) {
  7500. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  7501. }
  7502. return CanvasGraphics;
  7503. })();
  7504. exports.CanvasGraphics = CanvasGraphics;
  7505. exports.createScratchCanvas = createScratchCanvas;
  7506. }));
  7507. (function (root, factory) {
  7508. {
  7509. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  7510. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  7511. root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal);
  7512. }
  7513. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  7514. displayMetadata, sharedGlobal, amdRequire) {
  7515. var InvalidPDFException = sharedUtil.InvalidPDFException;
  7516. var MessageHandler = sharedUtil.MessageHandler;
  7517. var MissingPDFException = sharedUtil.MissingPDFException;
  7518. var PasswordResponses = sharedUtil.PasswordResponses;
  7519. var PasswordException = sharedUtil.PasswordException;
  7520. var StatTimer = sharedUtil.StatTimer;
  7521. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  7522. var UnknownErrorException = sharedUtil.UnknownErrorException;
  7523. var Util = sharedUtil.Util;
  7524. var createPromiseCapability = sharedUtil.createPromiseCapability;
  7525. var combineUrl = sharedUtil.combineUrl;
  7526. var error = sharedUtil.error;
  7527. var deprecated = sharedUtil.deprecated;
  7528. var info = sharedUtil.info;
  7529. var isArrayBuffer = sharedUtil.isArrayBuffer;
  7530. var isSameOrigin = sharedUtil.isSameOrigin;
  7531. var loadJpegStream = sharedUtil.loadJpegStream;
  7532. var stringToBytes = sharedUtil.stringToBytes;
  7533. var warn = sharedUtil.warn;
  7534. var FontFaceObject = displayFontLoader.FontFaceObject;
  7535. var FontLoader = displayFontLoader.FontLoader;
  7536. var CanvasGraphics = displayCanvas.CanvasGraphics;
  7537. var createScratchCanvas = displayCanvas.createScratchCanvas;
  7538. var Metadata = displayMetadata.Metadata;
  7539. var PDFJS = sharedGlobal.PDFJS;
  7540. var globalScope = sharedGlobal.globalScope;
  7541. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  7542. var useRequireEnsure = false;
  7543. if (typeof module !== 'undefined' && module.require) {
  7544. // node.js - disable worker and set require.ensure.
  7545. PDFJS.disableWorker = true;
  7546. if (typeof require.ensure === 'undefined') {
  7547. require.ensure = require('node-ensure');
  7548. }
  7549. useRequireEnsure = true;
  7550. }
  7551. if (typeof __webpack_require__ !== 'undefined') {
  7552. // Webpack - get/bundle pdf.worker.js as additional file.
  7553. PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js');
  7554. useRequireEnsure = true;
  7555. }
  7556. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  7557. PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  7558. }
  7559. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  7560. require.ensure([], function () {
  7561. require('./pdf.worker.js');
  7562. callback();
  7563. });
  7564. }) : (typeof requirejs !== 'undefined') ? (function (callback) {
  7565. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  7566. callback();
  7567. });
  7568. }) : null;
  7569. /**
  7570. * The maximum allowed image size in total pixels e.g. width * height. Images
  7571. * above this value will not be drawn. Use -1 for no limit.
  7572. * @var {number}
  7573. */
  7574. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  7575. -1 : PDFJS.maxImageSize);
  7576. /**
  7577. * The url of where the predefined Adobe CMaps are located. Include trailing
  7578. * slash.
  7579. * @var {string}
  7580. */
  7581. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  7582. /**
  7583. * Specifies if CMaps are binary packed.
  7584. * @var {boolean}
  7585. */
  7586. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  7587. /**
  7588. * By default fonts are converted to OpenType fonts and loaded via font face
  7589. * rules. If disabled, the font will be rendered using a built in font renderer
  7590. * that constructs the glyphs with primitive path commands.
  7591. * @var {boolean}
  7592. */
  7593. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  7594. false : PDFJS.disableFontFace);
  7595. /**
  7596. * Path for image resources, mainly for annotation icons. Include trailing
  7597. * slash.
  7598. * @var {string}
  7599. */
  7600. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  7601. '' : PDFJS.imageResourcesPath);
  7602. /**
  7603. * Disable the web worker and run all code on the main thread. This will happen
  7604. * automatically if the browser doesn't support workers or sending typed arrays
  7605. * to workers.
  7606. * @var {boolean}
  7607. */
  7608. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  7609. false : PDFJS.disableWorker);
  7610. /**
  7611. * Path and filename of the worker file. Required when the worker is enabled in
  7612. * development mode. If unspecified in the production build, the worker will be
  7613. * loaded based on the location of the pdf.js file. It is recommended that
  7614. * the workerSrc is set in a custom application to prevent issues caused by
  7615. * third-party frameworks and libraries.
  7616. * @var {string}
  7617. */
  7618. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  7619. /**
  7620. * Disable range request loading of PDF files. When enabled and if the server
  7621. * supports partial content requests then the PDF will be fetched in chunks.
  7622. * Enabled (false) by default.
  7623. * @var {boolean}
  7624. */
  7625. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  7626. false : PDFJS.disableRange);
  7627. /**
  7628. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  7629. * in chunks. This default behavior can be disabled.
  7630. * @var {boolean}
  7631. */
  7632. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  7633. false : PDFJS.disableStream);
  7634. /**
  7635. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  7636. * will automatically keep fetching more data even if it isn't needed to display
  7637. * the current page. This default behavior can be disabled.
  7638. *
  7639. * NOTE: It is also necessary to disable streaming, see above,
  7640. * in order for disabling of pre-fetching to work correctly.
  7641. * @var {boolean}
  7642. */
  7643. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  7644. false : PDFJS.disableAutoFetch);
  7645. /**
  7646. * Enables special hooks for debugging PDF.js.
  7647. * @var {boolean}
  7648. */
  7649. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  7650. /**
  7651. * Enables transfer usage in postMessage for ArrayBuffers.
  7652. * @var {boolean}
  7653. */
  7654. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  7655. true : PDFJS.postMessageTransfers);
  7656. /**
  7657. * Disables URL.createObjectURL usage.
  7658. * @var {boolean}
  7659. */
  7660. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  7661. false : PDFJS.disableCreateObjectURL);
  7662. /**
  7663. * Disables WebGL usage.
  7664. * @var {boolean}
  7665. */
  7666. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  7667. true : PDFJS.disableWebGL);
  7668. /**
  7669. * Disables fullscreen support, and by extension Presentation Mode,
  7670. * in browsers which support the fullscreen API.
  7671. * @var {boolean}
  7672. */
  7673. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  7674. false : PDFJS.disableFullscreen);
  7675. /**
  7676. * Enables CSS only zooming.
  7677. * @var {boolean}
  7678. */
  7679. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  7680. false : PDFJS.useOnlyCssZoom);
  7681. /**
  7682. * Controls the logging level.
  7683. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  7684. * - errors
  7685. * - warnings [default]
  7686. * - infos
  7687. * @var {number}
  7688. */
  7689. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  7690. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  7691. /**
  7692. * The maximum supported canvas size in total pixels e.g. width * height.
  7693. * The default value is 4096 * 4096. Use -1 for no limit.
  7694. * @var {number}
  7695. */
  7696. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  7697. 16777216 : PDFJS.maxCanvasPixels);
  7698. /**
  7699. * (Deprecated) Opens external links in a new window if enabled.
  7700. * The default behavior opens external links in the PDF.js window.
  7701. *
  7702. * NOTE: This property has been deprecated, please use
  7703. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  7704. * @var {boolean}
  7705. */
  7706. PDFJS.openExternalLinksInNewWindow = (
  7707. PDFJS.openExternalLinksInNewWindow === undefined ?
  7708. false : PDFJS.openExternalLinksInNewWindow);
  7709. /**
  7710. * Specifies the |target| attribute for external links.
  7711. * The constants from PDFJS.LinkTarget should be used:
  7712. * - NONE [default]
  7713. * - SELF
  7714. * - BLANK
  7715. * - PARENT
  7716. * - TOP
  7717. * @var {number}
  7718. */
  7719. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  7720. PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget);
  7721. /**
  7722. * Specifies the |rel| attribute for external links. Defaults to stripping
  7723. * the referrer.
  7724. * @var {string}
  7725. */
  7726. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  7727. 'noreferrer' : PDFJS.externalLinkRel);
  7728. /**
  7729. * Determines if we can eval strings as JS. Primarily used to improve
  7730. * performance for font rendering.
  7731. * @var {boolean}
  7732. */
  7733. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  7734. true : PDFJS.isEvalSupported);
  7735. /**
  7736. * Document initialization / loading parameters object.
  7737. *
  7738. * @typedef {Object} DocumentInitParameters
  7739. * @property {string} url - The URL of the PDF.
  7740. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  7741. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  7742. * use atob() to convert it to a binary string first.
  7743. * @property {Object} httpHeaders - Basic authentication headers.
  7744. * @property {boolean} withCredentials - Indicates whether or not cross-site
  7745. * Access-Control requests should be made using credentials such as cookies
  7746. * or authorization headers. The default is false.
  7747. * @property {string} password - For decrypting password-protected PDFs.
  7748. * @property {TypedArray} initialData - A typed array with the first portion or
  7749. * all of the pdf data. Used by the extension since some data is already
  7750. * loaded before the switch to range requests.
  7751. * @property {number} length - The PDF file length. It's used for progress
  7752. * reports and range requests operations.
  7753. * @property {PDFDataRangeTransport} range
  7754. * @property {number} rangeChunkSize - Optional parameter to specify
  7755. * maximum number of bytes fetched per range request. The default value is
  7756. * 2^16 = 65536.
  7757. * @property {PDFWorker} worker - The worker that will be used for the loading
  7758. * and parsing of the PDF data.
  7759. */
  7760. /**
  7761. * @typedef {Object} PDFDocumentStats
  7762. * @property {Array} streamTypes - Used stream types in the document (an item
  7763. * is set to true if specific stream ID was used in the document).
  7764. * @property {Array} fontTypes - Used font type in the document (an item is set
  7765. * to true if specific font ID was used in the document).
  7766. */
  7767. /**
  7768. * This is the main entry point for loading a PDF and interacting with it.
  7769. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  7770. * is used, which means it must follow the same origin rules that any XHR does
  7771. * e.g. No cross domain requests without CORS.
  7772. *
  7773. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  7774. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  7775. * already populated with data or parameter object.
  7776. *
  7777. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  7778. * if you want to manually serve range requests for data in the PDF.
  7779. *
  7780. * @param {function} passwordCallback (deprecated) It is used to request a
  7781. * password if wrong or no password was provided. The callback receives two
  7782. * parameters: function that needs to be called with new password and reason
  7783. * (see {PasswordResponses}).
  7784. *
  7785. * @param {function} progressCallback (deprecated) It is used to be able to
  7786. * monitor the loading progress of the PDF file (necessary to implement e.g.
  7787. * a loading bar). The callback receives an {Object} with the properties:
  7788. * {number} loaded and {number} total.
  7789. *
  7790. * @return {PDFDocumentLoadingTask}
  7791. */
  7792. PDFJS.getDocument = function getDocument(src,
  7793. pdfDataRangeTransport,
  7794. passwordCallback,
  7795. progressCallback) {
  7796. var task = new PDFDocumentLoadingTask();
  7797. // Support of the obsolete arguments (for compatibility with API v1.0)
  7798. if (arguments.length > 1) {
  7799. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  7800. 'passwordCallback or progressCallback argument');
  7801. }
  7802. if (pdfDataRangeTransport) {
  7803. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  7804. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  7805. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  7806. pdfDataRangeTransport.length = src.length;
  7807. pdfDataRangeTransport.initialData = src.initialData;
  7808. if (!pdfDataRangeTransport.abort) {
  7809. pdfDataRangeTransport.abort = function () {};
  7810. }
  7811. }
  7812. src = Object.create(src);
  7813. src.range = pdfDataRangeTransport;
  7814. }
  7815. task.onPassword = passwordCallback || null;
  7816. task.onProgress = progressCallback || null;
  7817. var source;
  7818. if (typeof src === 'string') {
  7819. source = { url: src };
  7820. } else if (isArrayBuffer(src)) {
  7821. source = { data: src };
  7822. } else if (src instanceof PDFDataRangeTransport) {
  7823. source = { range: src };
  7824. } else {
  7825. if (typeof src !== 'object') {
  7826. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  7827. 'string or a parameter object');
  7828. }
  7829. if (!src.url && !src.data && !src.range) {
  7830. error('Invalid parameter object: need either .data, .range or .url');
  7831. }
  7832. source = src;
  7833. }
  7834. var params = {};
  7835. var rangeTransport = null;
  7836. var worker = null;
  7837. for (var key in source) {
  7838. if (key === 'url' && typeof window !== 'undefined') {
  7839. // The full path is required in the 'url' field.
  7840. params[key] = combineUrl(window.location.href, source[key]);
  7841. continue;
  7842. } else if (key === 'range') {
  7843. rangeTransport = source[key];
  7844. continue;
  7845. } else if (key === 'worker') {
  7846. worker = source[key];
  7847. continue;
  7848. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  7849. // Converting string or array-like data to Uint8Array.
  7850. var pdfBytes = source[key];
  7851. if (typeof pdfBytes === 'string') {
  7852. params[key] = stringToBytes(pdfBytes);
  7853. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  7854. !isNaN(pdfBytes.length)) {
  7855. params[key] = new Uint8Array(pdfBytes);
  7856. } else if (isArrayBuffer(pdfBytes)) {
  7857. params[key] = new Uint8Array(pdfBytes);
  7858. } else {
  7859. error('Invalid PDF binary data: either typed array, string or ' +
  7860. 'array-like object is expected in the data property.');
  7861. }
  7862. continue;
  7863. }
  7864. params[key] = source[key];
  7865. }
  7866. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  7867. if (!worker) {
  7868. // Worker was not provided -- creating and owning our own.
  7869. worker = new PDFWorker();
  7870. task._worker = worker;
  7871. }
  7872. var docId = task.docId;
  7873. worker.promise.then(function () {
  7874. if (task.destroyed) {
  7875. throw new Error('Loading aborted');
  7876. }
  7877. return _fetchDocument(worker, params, rangeTransport, docId).then(
  7878. function (workerId) {
  7879. if (task.destroyed) {
  7880. throw new Error('Loading aborted');
  7881. }
  7882. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  7883. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  7884. task._transport = transport;
  7885. messageHandler.send('Ready', null);
  7886. });
  7887. }).catch(task._capability.reject);
  7888. return task;
  7889. };
  7890. /**
  7891. * Starts fetching of specified PDF document/data.
  7892. * @param {PDFWorker} worker
  7893. * @param {Object} source
  7894. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  7895. * @param {string} docId Unique document id, used as MessageHandler id.
  7896. * @returns {Promise} The promise, which is resolved when worker id of
  7897. * MessageHandler is known.
  7898. * @private
  7899. */
  7900. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  7901. if (worker.destroyed) {
  7902. return Promise.reject(new Error('Worker was destroyed'));
  7903. }
  7904. source.disableAutoFetch = PDFJS.disableAutoFetch;
  7905. source.disableStream = PDFJS.disableStream;
  7906. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  7907. if (pdfDataRangeTransport) {
  7908. source.length = pdfDataRangeTransport.length;
  7909. source.initialData = pdfDataRangeTransport.initialData;
  7910. }
  7911. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  7912. docId: docId,
  7913. source: source,
  7914. disableRange: PDFJS.disableRange,
  7915. maxImageSize: PDFJS.maxImageSize,
  7916. cMapUrl: PDFJS.cMapUrl,
  7917. cMapPacked: PDFJS.cMapPacked,
  7918. disableFontFace: PDFJS.disableFontFace,
  7919. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  7920. verbosity: PDFJS.verbosity,
  7921. postMessageTransfers: PDFJS.postMessageTransfers,
  7922. }).then(function (workerId) {
  7923. if (worker.destroyed) {
  7924. throw new Error('Worker was destroyed');
  7925. }
  7926. return workerId;
  7927. });
  7928. }
  7929. /**
  7930. * PDF document loading operation.
  7931. * @class
  7932. * @alias PDFDocumentLoadingTask
  7933. */
  7934. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  7935. var nextDocumentId = 0;
  7936. /** @constructs PDFDocumentLoadingTask */
  7937. function PDFDocumentLoadingTask() {
  7938. this._capability = createPromiseCapability();
  7939. this._transport = null;
  7940. this._worker = null;
  7941. /**
  7942. * Unique document loading task id -- used in MessageHandlers.
  7943. * @type {string}
  7944. */
  7945. this.docId = 'd' + (nextDocumentId++);
  7946. /**
  7947. * Shows if loading task is destroyed.
  7948. * @type {boolean}
  7949. */
  7950. this.destroyed = false;
  7951. /**
  7952. * Callback to request a password if wrong or no password was provided.
  7953. * The callback receives two parameters: function that needs to be called
  7954. * with new password and reason (see {PasswordResponses}).
  7955. */
  7956. this.onPassword = null;
  7957. /**
  7958. * Callback to be able to monitor the loading progress of the PDF file
  7959. * (necessary to implement e.g. a loading bar). The callback receives
  7960. * an {Object} with the properties: {number} loaded and {number} total.
  7961. */
  7962. this.onProgress = null;
  7963. /**
  7964. * Callback to when unsupported feature is used. The callback receives
  7965. * an {PDFJS.UNSUPPORTED_FEATURES} argument.
  7966. */
  7967. this.onUnsupportedFeature = null;
  7968. }
  7969. PDFDocumentLoadingTask.prototype =
  7970. /** @lends PDFDocumentLoadingTask.prototype */ {
  7971. /**
  7972. * @return {Promise}
  7973. */
  7974. get promise() {
  7975. return this._capability.promise;
  7976. },
  7977. /**
  7978. * Aborts all network requests and destroys worker.
  7979. * @return {Promise} A promise that is resolved after destruction activity
  7980. * is completed.
  7981. */
  7982. destroy: function () {
  7983. this.destroyed = true;
  7984. var transportDestroyed = !this._transport ? Promise.resolve() :
  7985. this._transport.destroy();
  7986. return transportDestroyed.then(function () {
  7987. this._transport = null;
  7988. if (this._worker) {
  7989. this._worker.destroy();
  7990. this._worker = null;
  7991. }
  7992. }.bind(this));
  7993. },
  7994. /**
  7995. * Registers callbacks to indicate the document loading completion.
  7996. *
  7997. * @param {function} onFulfilled The callback for the loading completion.
  7998. * @param {function} onRejected The callback for the loading failure.
  7999. * @return {Promise} A promise that is resolved after the onFulfilled or
  8000. * onRejected callback.
  8001. */
  8002. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8003. return this.promise.then.apply(this.promise, arguments);
  8004. }
  8005. };
  8006. return PDFDocumentLoadingTask;
  8007. })();
  8008. /**
  8009. * Abstract class to support range requests file loading.
  8010. * @class
  8011. * @alias PDFJS.PDFDataRangeTransport
  8012. * @param {number} length
  8013. * @param {Uint8Array} initialData
  8014. */
  8015. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8016. function PDFDataRangeTransport(length, initialData) {
  8017. this.length = length;
  8018. this.initialData = initialData;
  8019. this._rangeListeners = [];
  8020. this._progressListeners = [];
  8021. this._progressiveReadListeners = [];
  8022. this._readyCapability = createPromiseCapability();
  8023. }
  8024. PDFDataRangeTransport.prototype =
  8025. /** @lends PDFDataRangeTransport.prototype */ {
  8026. addRangeListener:
  8027. function PDFDataRangeTransport_addRangeListener(listener) {
  8028. this._rangeListeners.push(listener);
  8029. },
  8030. addProgressListener:
  8031. function PDFDataRangeTransport_addProgressListener(listener) {
  8032. this._progressListeners.push(listener);
  8033. },
  8034. addProgressiveReadListener:
  8035. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8036. this._progressiveReadListeners.push(listener);
  8037. },
  8038. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8039. var listeners = this._rangeListeners;
  8040. for (var i = 0, n = listeners.length; i < n; ++i) {
  8041. listeners[i](begin, chunk);
  8042. }
  8043. },
  8044. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8045. this._readyCapability.promise.then(function () {
  8046. var listeners = this._progressListeners;
  8047. for (var i = 0, n = listeners.length; i < n; ++i) {
  8048. listeners[i](loaded);
  8049. }
  8050. }.bind(this));
  8051. },
  8052. onDataProgressiveRead:
  8053. function PDFDataRangeTransport_onDataProgress(chunk) {
  8054. this._readyCapability.promise.then(function () {
  8055. var listeners = this._progressiveReadListeners;
  8056. for (var i = 0, n = listeners.length; i < n; ++i) {
  8057. listeners[i](chunk);
  8058. }
  8059. }.bind(this));
  8060. },
  8061. transportReady: function PDFDataRangeTransport_transportReady() {
  8062. this._readyCapability.resolve();
  8063. },
  8064. requestDataRange:
  8065. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8066. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8067. },
  8068. abort: function PDFDataRangeTransport_abort() {
  8069. }
  8070. };
  8071. return PDFDataRangeTransport;
  8072. })();
  8073. PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
  8074. /**
  8075. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8076. * properties that can be read synchronously.
  8077. * @class
  8078. * @alias PDFDocumentProxy
  8079. */
  8080. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8081. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8082. this.pdfInfo = pdfInfo;
  8083. this.transport = transport;
  8084. this.loadingTask = loadingTask;
  8085. }
  8086. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8087. /**
  8088. * @return {number} Total number of pages the PDF contains.
  8089. */
  8090. get numPages() {
  8091. return this.pdfInfo.numPages;
  8092. },
  8093. /**
  8094. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8095. * unique.
  8096. */
  8097. get fingerprint() {
  8098. return this.pdfInfo.fingerprint;
  8099. },
  8100. /**
  8101. * @param {number} pageNumber The page number to get. The first page is 1.
  8102. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8103. * object.
  8104. */
  8105. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8106. return this.transport.getPage(pageNumber);
  8107. },
  8108. /**
  8109. * @param {{num: number, gen: number}} ref The page reference. Must have
  8110. * the 'num' and 'gen' properties.
  8111. * @return {Promise} A promise that is resolved with the page index that is
  8112. * associated with the reference.
  8113. */
  8114. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8115. return this.transport.getPageIndex(ref);
  8116. },
  8117. /**
  8118. * @return {Promise} A promise that is resolved with a lookup table for
  8119. * mapping named destinations to reference numbers.
  8120. *
  8121. * This can be slow for large documents: use getDestination instead
  8122. */
  8123. getDestinations: function PDFDocumentProxy_getDestinations() {
  8124. return this.transport.getDestinations();
  8125. },
  8126. /**
  8127. * @param {string} id The named destination to get.
  8128. * @return {Promise} A promise that is resolved with all information
  8129. * of the given named destination.
  8130. */
  8131. getDestination: function PDFDocumentProxy_getDestination(id) {
  8132. return this.transport.getDestination(id);
  8133. },
  8134. /**
  8135. * @return {Promise} A promise that is resolved with:
  8136. * an Array containing the pageLabels that correspond to the pageIndexes,
  8137. * or `null` when no pageLabels are present in the PDF file.
  8138. */
  8139. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8140. return this.transport.getPageLabels();
  8141. },
  8142. /**
  8143. * @return {Promise} A promise that is resolved with a lookup table for
  8144. * mapping named attachments to their content.
  8145. */
  8146. getAttachments: function PDFDocumentProxy_getAttachments() {
  8147. return this.transport.getAttachments();
  8148. },
  8149. /**
  8150. * @return {Promise} A promise that is resolved with an array of all the
  8151. * JavaScript strings in the name tree.
  8152. */
  8153. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8154. return this.transport.getJavaScript();
  8155. },
  8156. /**
  8157. * @return {Promise} A promise that is resolved with an {Array} that is a
  8158. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8159. * [
  8160. * {
  8161. * title: string,
  8162. * bold: boolean,
  8163. * italic: boolean,
  8164. * color: rgb Uint8Array,
  8165. * dest: dest obj,
  8166. * url: string,
  8167. * items: array of more items like this
  8168. * },
  8169. * ...
  8170. * ].
  8171. */
  8172. getOutline: function PDFDocumentProxy_getOutline() {
  8173. return this.transport.getOutline();
  8174. },
  8175. /**
  8176. * @return {Promise} A promise that is resolved with an {Object} that has
  8177. * info and metadata properties. Info is an {Object} filled with anything
  8178. * available in the information dictionary and similarly metadata is a
  8179. * {Metadata} object with information from the metadata section of the PDF.
  8180. */
  8181. getMetadata: function PDFDocumentProxy_getMetadata() {
  8182. return this.transport.getMetadata();
  8183. },
  8184. /**
  8185. * @return {Promise} A promise that is resolved with a TypedArray that has
  8186. * the raw data from the PDF.
  8187. */
  8188. getData: function PDFDocumentProxy_getData() {
  8189. return this.transport.getData();
  8190. },
  8191. /**
  8192. * @return {Promise} A promise that is resolved when the document's data
  8193. * is loaded. It is resolved with an {Object} that contains the length
  8194. * property that indicates size of the PDF data in bytes.
  8195. */
  8196. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8197. return this.transport.downloadInfoCapability.promise;
  8198. },
  8199. /**
  8200. * @return {Promise} A promise this is resolved with current stats about
  8201. * document structures (see {@link PDFDocumentStats}).
  8202. */
  8203. getStats: function PDFDocumentProxy_getStats() {
  8204. return this.transport.getStats();
  8205. },
  8206. /**
  8207. * Cleans up resources allocated by the document, e.g. created @font-face.
  8208. */
  8209. cleanup: function PDFDocumentProxy_cleanup() {
  8210. this.transport.startCleanup();
  8211. },
  8212. /**
  8213. * Destroys current document instance and terminates worker.
  8214. */
  8215. destroy: function PDFDocumentProxy_destroy() {
  8216. return this.loadingTask.destroy();
  8217. }
  8218. };
  8219. return PDFDocumentProxy;
  8220. })();
  8221. /**
  8222. * Page getTextContent parameters.
  8223. *
  8224. * @typedef {Object} getTextContentParameters
  8225. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8226. * whitespace with standard spaces (0x20). The default value is `false`.
  8227. */
  8228. /**
  8229. * Page text content.
  8230. *
  8231. * @typedef {Object} TextContent
  8232. * @property {array} items - array of {@link TextItem}
  8233. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8234. * name.
  8235. */
  8236. /**
  8237. * Page text content part.
  8238. *
  8239. * @typedef {Object} TextItem
  8240. * @property {string} str - text content.
  8241. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8242. * @property {array} transform - transformation matrix.
  8243. * @property {number} width - width in device space.
  8244. * @property {number} height - height in device space.
  8245. * @property {string} fontName - font name used by pdf.js for converted font.
  8246. */
  8247. /**
  8248. * Text style.
  8249. *
  8250. * @typedef {Object} TextStyle
  8251. * @property {number} ascent - font ascent.
  8252. * @property {number} descent - font descent.
  8253. * @property {boolean} vertical - text is in vertical mode.
  8254. * @property {string} fontFamily - possible font family
  8255. */
  8256. /**
  8257. * Page annotation parameters.
  8258. *
  8259. * @typedef {Object} GetAnnotationsParameters
  8260. * @param {string} intent - Determines the annotations that will be fetched,
  8261. * can be either 'display' (viewable annotations) or 'print'
  8262. * (printable annotations).
  8263. * If the parameter is omitted, all annotations are fetched.
  8264. */
  8265. /**
  8266. * Page render parameters.
  8267. *
  8268. * @typedef {Object} RenderParameters
  8269. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8270. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  8271. * calling of PDFPage.getViewport method.
  8272. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8273. * (default value is 'display').
  8274. * @property {Array} transform - (optional) Additional transform, applied
  8275. * just before viewport transform.
  8276. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8277. * endLayout and appendImage functions.
  8278. * @property {function} continueCallback - (deprecated) A function that will be
  8279. * called each time the rendering is paused. To continue
  8280. * rendering call the function that is the first argument
  8281. * to the callback.
  8282. */
  8283. /**
  8284. * PDF page operator list.
  8285. *
  8286. * @typedef {Object} PDFOperatorList
  8287. * @property {Array} fnArray - Array containing the operator functions.
  8288. * @property {Array} argsArray - Array containing the arguments of the
  8289. * functions.
  8290. */
  8291. /**
  8292. * Proxy to a PDFPage in the worker thread.
  8293. * @class
  8294. * @alias PDFPageProxy
  8295. */
  8296. var PDFPageProxy = (function PDFPageProxyClosure() {
  8297. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8298. this.pageIndex = pageIndex;
  8299. this.pageInfo = pageInfo;
  8300. this.transport = transport;
  8301. this.stats = new StatTimer();
  8302. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  8303. this.commonObjs = transport.commonObjs;
  8304. this.objs = new PDFObjects();
  8305. this.cleanupAfterRender = false;
  8306. this.pendingCleanup = false;
  8307. this.intentStates = Object.create(null);
  8308. this.destroyed = false;
  8309. }
  8310. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8311. /**
  8312. * @return {number} Page number of the page. First page is 1.
  8313. */
  8314. get pageNumber() {
  8315. return this.pageIndex + 1;
  8316. },
  8317. /**
  8318. * @return {number} The number of degrees the page is rotated clockwise.
  8319. */
  8320. get rotate() {
  8321. return this.pageInfo.rotate;
  8322. },
  8323. /**
  8324. * @return {Object} The reference that points to this page. It has 'num' and
  8325. * 'gen' properties.
  8326. */
  8327. get ref() {
  8328. return this.pageInfo.ref;
  8329. },
  8330. /**
  8331. * @return {Array} An array of the visible portion of the PDF page in the
  8332. * user space units - [x1, y1, x2, y2].
  8333. */
  8334. get view() {
  8335. return this.pageInfo.view;
  8336. },
  8337. /**
  8338. * @param {number} scale The desired scale of the viewport.
  8339. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8340. * defaults to the page rotation.
  8341. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  8342. * along with transforms required for rendering.
  8343. */
  8344. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8345. if (arguments.length < 2) {
  8346. rotate = this.rotate;
  8347. }
  8348. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  8349. },
  8350. /**
  8351. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8352. * @return {Promise} A promise that is resolved with an {Array} of the
  8353. * annotation objects.
  8354. */
  8355. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8356. var intent = (params && params.intent) || null;
  8357. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8358. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8359. intent);
  8360. this.annotationsIntent = intent;
  8361. }
  8362. return this.annotationsPromise;
  8363. },
  8364. /**
  8365. * Begins the process of rendering a page to the desired context.
  8366. * @param {RenderParameters} params Page render parameters.
  8367. * @return {RenderTask} An object that contains the promise, which
  8368. * is resolved when the page finishes rendering.
  8369. */
  8370. render: function PDFPageProxy_render(params) {
  8371. var stats = this.stats;
  8372. stats.time('Overall');
  8373. // If there was a pending destroy cancel it so no cleanup happens during
  8374. // this call to render.
  8375. this.pendingCleanup = false;
  8376. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8377. if (!this.intentStates[renderingIntent]) {
  8378. this.intentStates[renderingIntent] = Object.create(null);
  8379. }
  8380. var intentState = this.intentStates[renderingIntent];
  8381. // If there's no displayReadyCapability yet, then the operatorList
  8382. // was never requested before. Make the request and create the promise.
  8383. if (!intentState.displayReadyCapability) {
  8384. intentState.receivingOperatorList = true;
  8385. intentState.displayReadyCapability = createPromiseCapability();
  8386. intentState.operatorList = {
  8387. fnArray: [],
  8388. argsArray: [],
  8389. lastChunk: false
  8390. };
  8391. this.stats.time('Page Request');
  8392. this.transport.messageHandler.send('RenderPageRequest', {
  8393. pageIndex: this.pageNumber - 1,
  8394. intent: renderingIntent
  8395. });
  8396. }
  8397. var internalRenderTask = new InternalRenderTask(complete, params,
  8398. this.objs,
  8399. this.commonObjs,
  8400. intentState.operatorList,
  8401. this.pageNumber);
  8402. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8403. if (!intentState.renderTasks) {
  8404. intentState.renderTasks = [];
  8405. }
  8406. intentState.renderTasks.push(internalRenderTask);
  8407. var renderTask = internalRenderTask.task;
  8408. // Obsolete parameter support
  8409. if (params.continueCallback) {
  8410. deprecated('render is used with continueCallback parameter');
  8411. renderTask.onContinue = params.continueCallback;
  8412. }
  8413. var self = this;
  8414. intentState.displayReadyCapability.promise.then(
  8415. function pageDisplayReadyPromise(transparency) {
  8416. if (self.pendingCleanup) {
  8417. complete();
  8418. return;
  8419. }
  8420. stats.time('Rendering');
  8421. internalRenderTask.initalizeGraphics(transparency);
  8422. internalRenderTask.operatorListChanged();
  8423. },
  8424. function pageDisplayReadPromiseError(reason) {
  8425. complete(reason);
  8426. }
  8427. );
  8428. function complete(error) {
  8429. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8430. if (i >= 0) {
  8431. intentState.renderTasks.splice(i, 1);
  8432. }
  8433. if (self.cleanupAfterRender) {
  8434. self.pendingCleanup = true;
  8435. }
  8436. self._tryCleanup();
  8437. if (error) {
  8438. internalRenderTask.capability.reject(error);
  8439. } else {
  8440. internalRenderTask.capability.resolve();
  8441. }
  8442. stats.timeEnd('Rendering');
  8443. stats.timeEnd('Overall');
  8444. }
  8445. return renderTask;
  8446. },
  8447. /**
  8448. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8449. * object that represents page's operator list.
  8450. */
  8451. getOperatorList: function PDFPageProxy_getOperatorList() {
  8452. function operatorListChanged() {
  8453. if (intentState.operatorList.lastChunk) {
  8454. intentState.opListReadCapability.resolve(intentState.operatorList);
  8455. var i = intentState.renderTasks.indexOf(opListTask);
  8456. if (i >= 0) {
  8457. intentState.renderTasks.splice(i, 1);
  8458. }
  8459. }
  8460. }
  8461. var renderingIntent = 'oplist';
  8462. if (!this.intentStates[renderingIntent]) {
  8463. this.intentStates[renderingIntent] = Object.create(null);
  8464. }
  8465. var intentState = this.intentStates[renderingIntent];
  8466. var opListTask;
  8467. if (!intentState.opListReadCapability) {
  8468. opListTask = {};
  8469. opListTask.operatorListChanged = operatorListChanged;
  8470. intentState.receivingOperatorList = true;
  8471. intentState.opListReadCapability = createPromiseCapability();
  8472. intentState.renderTasks = [];
  8473. intentState.renderTasks.push(opListTask);
  8474. intentState.operatorList = {
  8475. fnArray: [],
  8476. argsArray: [],
  8477. lastChunk: false
  8478. };
  8479. this.transport.messageHandler.send('RenderPageRequest', {
  8480. pageIndex: this.pageIndex,
  8481. intent: renderingIntent
  8482. });
  8483. }
  8484. return intentState.opListReadCapability.promise;
  8485. },
  8486. /**
  8487. * @param {getTextContentParameters} params - getTextContent parameters.
  8488. * @return {Promise} That is resolved a {@link TextContent}
  8489. * object that represent the page text content.
  8490. */
  8491. getTextContent: function PDFPageProxy_getTextContent(params) {
  8492. var normalizeWhitespace = (params && params.normalizeWhitespace) || false;
  8493. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8494. pageIndex: this.pageNumber - 1,
  8495. normalizeWhitespace: normalizeWhitespace,
  8496. });
  8497. },
  8498. /**
  8499. * Destroys page object.
  8500. */
  8501. _destroy: function PDFPageProxy_destroy() {
  8502. this.destroyed = true;
  8503. this.transport.pageCache[this.pageIndex] = null;
  8504. var waitOn = [];
  8505. Object.keys(this.intentStates).forEach(function(intent) {
  8506. if (intent === 'oplist') {
  8507. // Avoid errors below, since the renderTasks are just stubs.
  8508. return;
  8509. }
  8510. var intentState = this.intentStates[intent];
  8511. intentState.renderTasks.forEach(function(renderTask) {
  8512. var renderCompleted = renderTask.capability.promise.
  8513. catch(function () {}); // ignoring failures
  8514. waitOn.push(renderCompleted);
  8515. renderTask.cancel();
  8516. });
  8517. }, this);
  8518. this.objs.clear();
  8519. this.annotationsPromise = null;
  8520. this.pendingCleanup = false;
  8521. return Promise.all(waitOn);
  8522. },
  8523. /**
  8524. * Cleans up resources allocated by the page. (deprecated)
  8525. */
  8526. destroy: function() {
  8527. deprecated('page destroy method, use cleanup() instead');
  8528. this.cleanup();
  8529. },
  8530. /**
  8531. * Cleans up resources allocated by the page.
  8532. */
  8533. cleanup: function PDFPageProxy_cleanup() {
  8534. this.pendingCleanup = true;
  8535. this._tryCleanup();
  8536. },
  8537. /**
  8538. * For internal use only. Attempts to clean up if rendering is in a state
  8539. * where that's possible.
  8540. * @ignore
  8541. */
  8542. _tryCleanup: function PDFPageProxy_tryCleanup() {
  8543. if (!this.pendingCleanup ||
  8544. Object.keys(this.intentStates).some(function(intent) {
  8545. var intentState = this.intentStates[intent];
  8546. return (intentState.renderTasks.length !== 0 ||
  8547. intentState.receivingOperatorList);
  8548. }, this)) {
  8549. return;
  8550. }
  8551. Object.keys(this.intentStates).forEach(function(intent) {
  8552. delete this.intentStates[intent];
  8553. }, this);
  8554. this.objs.clear();
  8555. this.annotationsPromise = null;
  8556. this.pendingCleanup = false;
  8557. },
  8558. /**
  8559. * For internal use only.
  8560. * @ignore
  8561. */
  8562. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  8563. intent) {
  8564. var intentState = this.intentStates[intent];
  8565. // TODO Refactor RenderPageRequest to separate rendering
  8566. // and operator list logic
  8567. if (intentState.displayReadyCapability) {
  8568. intentState.displayReadyCapability.resolve(transparency);
  8569. }
  8570. },
  8571. /**
  8572. * For internal use only.
  8573. * @ignore
  8574. */
  8575. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  8576. intent) {
  8577. var intentState = this.intentStates[intent];
  8578. var i, ii;
  8579. // Add the new chunk to the current operator list.
  8580. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  8581. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  8582. intentState.operatorList.argsArray.push(
  8583. operatorListChunk.argsArray[i]);
  8584. }
  8585. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  8586. // Notify all the rendering tasks there are more operators to be consumed.
  8587. for (i = 0; i < intentState.renderTasks.length; i++) {
  8588. intentState.renderTasks[i].operatorListChanged();
  8589. }
  8590. if (operatorListChunk.lastChunk) {
  8591. intentState.receivingOperatorList = false;
  8592. this._tryCleanup();
  8593. }
  8594. }
  8595. };
  8596. return PDFPageProxy;
  8597. })();
  8598. /**
  8599. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  8600. * WorkerTransport for them. If creation of a web worker is not possible,
  8601. * a "fake" worker will be used instead.
  8602. * @class
  8603. */
  8604. var PDFWorker = (function PDFWorkerClosure() {
  8605. var nextFakeWorkerId = 0;
  8606. function getWorkerSrc() {
  8607. if (PDFJS.workerSrc) {
  8608. return PDFJS.workerSrc;
  8609. }
  8610. if (pdfjsFilePath) {
  8611. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  8612. }
  8613. error('No PDFJS.workerSrc specified');
  8614. }
  8615. // Loads worker code into main thread.
  8616. function setupFakeWorkerGlobal() {
  8617. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  8618. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  8619. // In the developer build load worker_loader which in turn loads all the
  8620. // other files and resolves the promise. In production only the
  8621. // pdf.worker.js file is needed.
  8622. var loader = fakeWorkerFilesLoader || function (callback) {
  8623. Util.loadScript(getWorkerSrc(), callback);
  8624. };
  8625. loader(function () {
  8626. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  8627. });
  8628. }
  8629. return PDFJS.fakeWorkerFilesLoadedCapability.promise;
  8630. }
  8631. function createCDNWrapper(url) {
  8632. // We will rely on blob URL's property to specify origin.
  8633. // We want this function to fail in case if createObjectURL or Blob do not
  8634. // exist or fail for some reason -- our Worker creation will fail anyway.
  8635. var wrapper = 'importScripts(\'' + url + '\');';
  8636. return URL.createObjectURL(new Blob([wrapper]));
  8637. }
  8638. function PDFWorker(name) {
  8639. this.name = name;
  8640. this.destroyed = false;
  8641. this._readyCapability = createPromiseCapability();
  8642. this._port = null;
  8643. this._webWorker = null;
  8644. this._messageHandler = null;
  8645. this._initialize();
  8646. }
  8647. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  8648. get promise() {
  8649. return this._readyCapability.promise;
  8650. },
  8651. get port() {
  8652. return this._port;
  8653. },
  8654. get messageHandler() {
  8655. return this._messageHandler;
  8656. },
  8657. _initialize: function PDFWorker_initialize() {
  8658. // If worker support isn't disabled explicit and the browser has worker
  8659. // support, create a new web worker and test if it/the browser fulfills
  8660. // all requirements to run parts of pdf.js in a web worker.
  8661. // Right now, the requirement is, that an Uint8Array is still an
  8662. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  8663. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  8664. var workerSrc = getWorkerSrc();
  8665. try {
  8666. // Wraps workerSrc path into blob URL, if the former does not belong
  8667. // to the same origin.
  8668. if (!isSameOrigin(window.location.href, workerSrc)) {
  8669. workerSrc = createCDNWrapper(
  8670. combineUrl(window.location.href, workerSrc));
  8671. }
  8672. // Some versions of FF can't create a worker on localhost, see:
  8673. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  8674. var worker = new Worker(workerSrc);
  8675. var messageHandler = new MessageHandler('main', 'worker', worker);
  8676. messageHandler.on('test', function PDFWorker_test(data) {
  8677. if (this.destroyed) {
  8678. this._readyCapability.reject(new Error('Worker was destroyed'));
  8679. messageHandler.destroy();
  8680. worker.terminate();
  8681. return; // worker was destroyed
  8682. }
  8683. var supportTypedArray = data && data.supportTypedArray;
  8684. if (supportTypedArray) {
  8685. this._messageHandler = messageHandler;
  8686. this._port = worker;
  8687. this._webWorker = worker;
  8688. if (!data.supportTransfers) {
  8689. PDFJS.postMessageTransfers = false;
  8690. }
  8691. this._readyCapability.resolve();
  8692. } else {
  8693. this._setupFakeWorker();
  8694. messageHandler.destroy();
  8695. worker.terminate();
  8696. }
  8697. }.bind(this));
  8698. messageHandler.on('console_log', function (data) {
  8699. console.log.apply(console, data);
  8700. });
  8701. messageHandler.on('console_error', function (data) {
  8702. console.error.apply(console, data);
  8703. });
  8704. messageHandler.on('ready', function (data) {
  8705. if (this.destroyed) {
  8706. this._readyCapability.reject(new Error('Worker was destroyed'));
  8707. messageHandler.destroy();
  8708. worker.terminate();
  8709. return; // worker was destroyed
  8710. }
  8711. try {
  8712. sendTest();
  8713. } catch (e) {
  8714. // We need fallback to a faked worker.
  8715. this._setupFakeWorker();
  8716. }
  8717. }.bind(this));
  8718. var sendTest = function () {
  8719. var testObj = new Uint8Array(
  8720. [PDFJS.postMessageTransfers ? 255 : 0]);
  8721. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  8722. // typed array. Also, checking if we can use transfers.
  8723. try {
  8724. messageHandler.send('test', testObj, [testObj.buffer]);
  8725. } catch (ex) {
  8726. info('Cannot use postMessage transfers');
  8727. testObj[0] = 0;
  8728. messageHandler.send('test', testObj);
  8729. }
  8730. };
  8731. // It might take time for worker to initialize (especially when AMD
  8732. // loader is used). We will try to send test immediately, and then
  8733. // when 'ready' message will arrive. The worker shall process only
  8734. // first received 'test'.
  8735. sendTest();
  8736. return;
  8737. } catch (e) {
  8738. info('The worker has been disabled.');
  8739. }
  8740. }
  8741. // Either workers are disabled, not supported or have thrown an exception.
  8742. // Thus, we fallback to a faked worker.
  8743. this._setupFakeWorker();
  8744. },
  8745. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  8746. if (!globalScope.PDFJS.disableWorker) {
  8747. warn('Setting up fake worker.');
  8748. globalScope.PDFJS.disableWorker = true;
  8749. }
  8750. setupFakeWorkerGlobal().then(function () {
  8751. if (this.destroyed) {
  8752. this._readyCapability.reject(new Error('Worker was destroyed'));
  8753. return;
  8754. }
  8755. // If we don't use a worker, just post/sendMessage to the main thread.
  8756. var port = {
  8757. _listeners: [],
  8758. postMessage: function (obj) {
  8759. var e = {data: obj};
  8760. this._listeners.forEach(function (listener) {
  8761. listener.call(this, e);
  8762. }, this);
  8763. },
  8764. addEventListener: function (name, listener) {
  8765. this._listeners.push(listener);
  8766. },
  8767. removeEventListener: function (name, listener) {
  8768. var i = this._listeners.indexOf(listener);
  8769. this._listeners.splice(i, 1);
  8770. },
  8771. terminate: function () {}
  8772. };
  8773. this._port = port;
  8774. // All fake workers use the same port, making id unique.
  8775. var id = 'fake' + (nextFakeWorkerId++);
  8776. // If the main thread is our worker, setup the handling for the
  8777. // messages -- the main thread sends to it self.
  8778. var workerHandler = new MessageHandler(id + '_worker', id, port);
  8779. PDFJS.WorkerMessageHandler.setup(workerHandler, port);
  8780. var messageHandler = new MessageHandler(id, id + '_worker', port);
  8781. this._messageHandler = messageHandler;
  8782. this._readyCapability.resolve();
  8783. }.bind(this));
  8784. },
  8785. /**
  8786. * Destroys the worker instance.
  8787. */
  8788. destroy: function PDFWorker_destroy() {
  8789. this.destroyed = true;
  8790. if (this._webWorker) {
  8791. // We need to terminate only web worker created resource.
  8792. this._webWorker.terminate();
  8793. this._webWorker = null;
  8794. }
  8795. this._port = null;
  8796. if (this._messageHandler) {
  8797. this._messageHandler.destroy();
  8798. this._messageHandler = null;
  8799. }
  8800. }
  8801. };
  8802. return PDFWorker;
  8803. })();
  8804. PDFJS.PDFWorker = PDFWorker;
  8805. /**
  8806. * For internal use only.
  8807. * @ignore
  8808. */
  8809. var WorkerTransport = (function WorkerTransportClosure() {
  8810. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  8811. this.messageHandler = messageHandler;
  8812. this.loadingTask = loadingTask;
  8813. this.pdfDataRangeTransport = pdfDataRangeTransport;
  8814. this.commonObjs = new PDFObjects();
  8815. this.fontLoader = new FontLoader(loadingTask.docId);
  8816. this.destroyed = false;
  8817. this.destroyCapability = null;
  8818. this.pageCache = [];
  8819. this.pagePromises = [];
  8820. this.downloadInfoCapability = createPromiseCapability();
  8821. this.setupMessageHandler();
  8822. }
  8823. WorkerTransport.prototype = {
  8824. destroy: function WorkerTransport_destroy() {
  8825. if (this.destroyCapability) {
  8826. return this.destroyCapability.promise;
  8827. }
  8828. this.destroyed = true;
  8829. this.destroyCapability = createPromiseCapability();
  8830. var waitOn = [];
  8831. // We need to wait for all renderings to be completed, e.g.
  8832. // timeout/rAF can take a long time.
  8833. this.pageCache.forEach(function (page) {
  8834. if (page) {
  8835. waitOn.push(page._destroy());
  8836. }
  8837. });
  8838. this.pageCache = [];
  8839. this.pagePromises = [];
  8840. var self = this;
  8841. // We also need to wait for the worker to finish its long running tasks.
  8842. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  8843. waitOn.push(terminated);
  8844. Promise.all(waitOn).then(function () {
  8845. self.fontLoader.clear();
  8846. if (self.pdfDataRangeTransport) {
  8847. self.pdfDataRangeTransport.abort();
  8848. self.pdfDataRangeTransport = null;
  8849. }
  8850. if (self.messageHandler) {
  8851. self.messageHandler.destroy();
  8852. self.messageHandler = null;
  8853. }
  8854. self.destroyCapability.resolve();
  8855. }, this.destroyCapability.reject);
  8856. return this.destroyCapability.promise;
  8857. },
  8858. setupMessageHandler:
  8859. function WorkerTransport_setupMessageHandler() {
  8860. var messageHandler = this.messageHandler;
  8861. function updatePassword(password) {
  8862. messageHandler.send('UpdatePassword', password);
  8863. }
  8864. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  8865. if (pdfDataRangeTransport) {
  8866. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  8867. messageHandler.send('OnDataRange', {
  8868. begin: begin,
  8869. chunk: chunk
  8870. });
  8871. });
  8872. pdfDataRangeTransport.addProgressListener(function(loaded) {
  8873. messageHandler.send('OnDataProgress', {
  8874. loaded: loaded
  8875. });
  8876. });
  8877. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  8878. messageHandler.send('OnDataRange', {
  8879. chunk: chunk
  8880. });
  8881. });
  8882. messageHandler.on('RequestDataRange',
  8883. function transportDataRange(data) {
  8884. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  8885. }, this);
  8886. }
  8887. messageHandler.on('GetDoc', function transportDoc(data) {
  8888. var pdfInfo = data.pdfInfo;
  8889. this.numPages = data.pdfInfo.numPages;
  8890. var loadingTask = this.loadingTask;
  8891. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  8892. this.pdfDocument = pdfDocument;
  8893. loadingTask._capability.resolve(pdfDocument);
  8894. }, this);
  8895. messageHandler.on('NeedPassword',
  8896. function transportNeedPassword(exception) {
  8897. var loadingTask = this.loadingTask;
  8898. if (loadingTask.onPassword) {
  8899. return loadingTask.onPassword(updatePassword,
  8900. PasswordResponses.NEED_PASSWORD);
  8901. }
  8902. loadingTask._capability.reject(
  8903. new PasswordException(exception.message, exception.code));
  8904. }, this);
  8905. messageHandler.on('IncorrectPassword',
  8906. function transportIncorrectPassword(exception) {
  8907. var loadingTask = this.loadingTask;
  8908. if (loadingTask.onPassword) {
  8909. return loadingTask.onPassword(updatePassword,
  8910. PasswordResponses.INCORRECT_PASSWORD);
  8911. }
  8912. loadingTask._capability.reject(
  8913. new PasswordException(exception.message, exception.code));
  8914. }, this);
  8915. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  8916. this.loadingTask._capability.reject(
  8917. new InvalidPDFException(exception.message));
  8918. }, this);
  8919. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  8920. this.loadingTask._capability.reject(
  8921. new MissingPDFException(exception.message));
  8922. }, this);
  8923. messageHandler.on('UnexpectedResponse',
  8924. function transportUnexpectedResponse(exception) {
  8925. this.loadingTask._capability.reject(
  8926. new UnexpectedResponseException(exception.message, exception.status));
  8927. }, this);
  8928. messageHandler.on('UnknownError',
  8929. function transportUnknownError(exception) {
  8930. this.loadingTask._capability.reject(
  8931. new UnknownErrorException(exception.message, exception.details));
  8932. }, this);
  8933. messageHandler.on('DataLoaded', function transportPage(data) {
  8934. this.downloadInfoCapability.resolve(data);
  8935. }, this);
  8936. messageHandler.on('PDFManagerReady', function transportPage(data) {
  8937. if (this.pdfDataRangeTransport) {
  8938. this.pdfDataRangeTransport.transportReady();
  8939. }
  8940. }, this);
  8941. messageHandler.on('StartRenderPage', function transportRender(data) {
  8942. if (this.destroyed) {
  8943. return; // Ignore any pending requests if the worker was terminated.
  8944. }
  8945. var page = this.pageCache[data.pageIndex];
  8946. page.stats.timeEnd('Page Request');
  8947. page._startRenderPage(data.transparency, data.intent);
  8948. }, this);
  8949. messageHandler.on('RenderPageChunk', function transportRender(data) {
  8950. if (this.destroyed) {
  8951. return; // Ignore any pending requests if the worker was terminated.
  8952. }
  8953. var page = this.pageCache[data.pageIndex];
  8954. page._renderPageChunk(data.operatorList, data.intent);
  8955. }, this);
  8956. messageHandler.on('commonobj', function transportObj(data) {
  8957. if (this.destroyed) {
  8958. return; // Ignore any pending requests if the worker was terminated.
  8959. }
  8960. var id = data[0];
  8961. var type = data[1];
  8962. if (this.commonObjs.hasData(id)) {
  8963. return;
  8964. }
  8965. switch (type) {
  8966. case 'Font':
  8967. var exportedData = data[2];
  8968. var font;
  8969. if ('error' in exportedData) {
  8970. var error = exportedData.error;
  8971. warn('Error during font loading: ' + error);
  8972. this.commonObjs.resolve(id, error);
  8973. break;
  8974. } else {
  8975. font = new FontFaceObject(exportedData);
  8976. }
  8977. this.fontLoader.bind(
  8978. [font],
  8979. function fontReady(fontObjs) {
  8980. this.commonObjs.resolve(id, font);
  8981. }.bind(this)
  8982. );
  8983. break;
  8984. case 'FontPath':
  8985. this.commonObjs.resolve(id, data[2]);
  8986. break;
  8987. default:
  8988. error('Got unknown common object type ' + type);
  8989. }
  8990. }, this);
  8991. messageHandler.on('obj', function transportObj(data) {
  8992. if (this.destroyed) {
  8993. return; // Ignore any pending requests if the worker was terminated.
  8994. }
  8995. var id = data[0];
  8996. var pageIndex = data[1];
  8997. var type = data[2];
  8998. var pageProxy = this.pageCache[pageIndex];
  8999. var imageData;
  9000. if (pageProxy.objs.hasData(id)) {
  9001. return;
  9002. }
  9003. switch (type) {
  9004. case 'JpegStream':
  9005. imageData = data[3];
  9006. loadJpegStream(id, imageData, pageProxy.objs);
  9007. break;
  9008. case 'Image':
  9009. imageData = data[3];
  9010. pageProxy.objs.resolve(id, imageData);
  9011. // heuristics that will allow not to store large data
  9012. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9013. if (imageData && 'data' in imageData &&
  9014. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9015. pageProxy.cleanupAfterRender = true;
  9016. }
  9017. break;
  9018. default:
  9019. error('Got unknown object type ' + type);
  9020. }
  9021. }, this);
  9022. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9023. if (this.destroyed) {
  9024. return; // Ignore any pending requests if the worker was terminated.
  9025. }
  9026. var loadingTask = this.loadingTask;
  9027. if (loadingTask.onProgress) {
  9028. loadingTask.onProgress({
  9029. loaded: data.loaded,
  9030. total: data.total
  9031. });
  9032. }
  9033. }, this);
  9034. messageHandler.on('PageError', function transportError(data) {
  9035. if (this.destroyed) {
  9036. return; // Ignore any pending requests if the worker was terminated.
  9037. }
  9038. var page = this.pageCache[data.pageNum - 1];
  9039. var intentState = page.intentStates[data.intent];
  9040. if (intentState.displayReadyCapability) {
  9041. intentState.displayReadyCapability.reject(data.error);
  9042. } else {
  9043. error(data.error);
  9044. }
  9045. }, this);
  9046. messageHandler.on('UnsupportedFeature',
  9047. function transportUnsupportedFeature(data) {
  9048. if (this.destroyed) {
  9049. return; // Ignore any pending requests if the worker was terminated.
  9050. }
  9051. var featureId = data.featureId;
  9052. var loadingTask = this.loadingTask;
  9053. if (loadingTask.onUnsupportedFeature) {
  9054. loadingTask.onUnsupportedFeature(featureId);
  9055. }
  9056. PDFJS.UnsupportedManager.notify(featureId);
  9057. }, this);
  9058. messageHandler.on('JpegDecode', function(data) {
  9059. if (this.destroyed) {
  9060. return Promise.reject('Worker was terminated');
  9061. }
  9062. var imageUrl = data[0];
  9063. var components = data[1];
  9064. if (components !== 3 && components !== 1) {
  9065. return Promise.reject(
  9066. new Error('Only 3 components or 1 component can be returned'));
  9067. }
  9068. return new Promise(function (resolve, reject) {
  9069. var img = new Image();
  9070. img.onload = function () {
  9071. var width = img.width;
  9072. var height = img.height;
  9073. var size = width * height;
  9074. var rgbaLength = size * 4;
  9075. var buf = new Uint8Array(size * components);
  9076. var tmpCanvas = createScratchCanvas(width, height);
  9077. var tmpCtx = tmpCanvas.getContext('2d');
  9078. tmpCtx.drawImage(img, 0, 0);
  9079. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9080. var i, j;
  9081. if (components === 3) {
  9082. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9083. buf[j] = data[i];
  9084. buf[j + 1] = data[i + 1];
  9085. buf[j + 2] = data[i + 2];
  9086. }
  9087. } else if (components === 1) {
  9088. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9089. buf[j] = data[i];
  9090. }
  9091. }
  9092. resolve({ data: buf, width: width, height: height});
  9093. };
  9094. img.onerror = function () {
  9095. reject(new Error('JpegDecode failed to load image'));
  9096. };
  9097. img.src = imageUrl;
  9098. });
  9099. }, this);
  9100. },
  9101. getData: function WorkerTransport_getData() {
  9102. return this.messageHandler.sendWithPromise('GetData', null);
  9103. },
  9104. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9105. if (pageNumber <= 0 || pageNumber > this.numPages ||
  9106. (pageNumber|0) !== pageNumber) {
  9107. return Promise.reject(new Error('Invalid page request'));
  9108. }
  9109. var pageIndex = pageNumber - 1;
  9110. if (pageIndex in this.pagePromises) {
  9111. return this.pagePromises[pageIndex];
  9112. }
  9113. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9114. pageIndex: pageIndex
  9115. }).then(function (pageInfo) {
  9116. if (this.destroyed) {
  9117. throw new Error('Transport destroyed');
  9118. }
  9119. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9120. this.pageCache[pageIndex] = page;
  9121. return page;
  9122. }.bind(this));
  9123. this.pagePromises[pageIndex] = promise;
  9124. return promise;
  9125. },
  9126. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9127. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  9128. },
  9129. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9130. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9131. pageIndex: pageIndex,
  9132. intent: intent,
  9133. });
  9134. },
  9135. getDestinations: function WorkerTransport_getDestinations() {
  9136. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9137. },
  9138. getDestination: function WorkerTransport_getDestination(id) {
  9139. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9140. },
  9141. getPageLabels: function WorkerTransport_getPageLabels() {
  9142. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9143. },
  9144. getAttachments: function WorkerTransport_getAttachments() {
  9145. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9146. },
  9147. getJavaScript: function WorkerTransport_getJavaScript() {
  9148. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9149. },
  9150. getOutline: function WorkerTransport_getOutline() {
  9151. return this.messageHandler.sendWithPromise('GetOutline', null);
  9152. },
  9153. getMetadata: function WorkerTransport_getMetadata() {
  9154. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9155. then(function transportMetadata(results) {
  9156. return {
  9157. info: results[0],
  9158. metadata: (results[1] ? new Metadata(results[1]) : null)
  9159. };
  9160. });
  9161. },
  9162. getStats: function WorkerTransport_getStats() {
  9163. return this.messageHandler.sendWithPromise('GetStats', null);
  9164. },
  9165. startCleanup: function WorkerTransport_startCleanup() {
  9166. this.messageHandler.sendWithPromise('Cleanup', null).
  9167. then(function endCleanup() {
  9168. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9169. var page = this.pageCache[i];
  9170. if (page) {
  9171. page.cleanup();
  9172. }
  9173. }
  9174. this.commonObjs.clear();
  9175. this.fontLoader.clear();
  9176. }.bind(this));
  9177. }
  9178. };
  9179. return WorkerTransport;
  9180. })();
  9181. /**
  9182. * A PDF document and page is built of many objects. E.g. there are objects
  9183. * for fonts, images, rendering code and such. These objects might get processed
  9184. * inside of a worker. The `PDFObjects` implements some basic functions to
  9185. * manage these objects.
  9186. * @ignore
  9187. */
  9188. var PDFObjects = (function PDFObjectsClosure() {
  9189. function PDFObjects() {
  9190. this.objs = Object.create(null);
  9191. }
  9192. PDFObjects.prototype = {
  9193. /**
  9194. * Internal function.
  9195. * Ensures there is an object defined for `objId`.
  9196. */
  9197. ensureObj: function PDFObjects_ensureObj(objId) {
  9198. if (this.objs[objId]) {
  9199. return this.objs[objId];
  9200. }
  9201. var obj = {
  9202. capability: createPromiseCapability(),
  9203. data: null,
  9204. resolved: false
  9205. };
  9206. this.objs[objId] = obj;
  9207. return obj;
  9208. },
  9209. /**
  9210. * If called *without* callback, this returns the data of `objId` but the
  9211. * object needs to be resolved. If it isn't, this function throws.
  9212. *
  9213. * If called *with* a callback, the callback is called with the data of the
  9214. * object once the object is resolved. That means, if you call this
  9215. * function and the object is already resolved, the callback gets called
  9216. * right away.
  9217. */
  9218. get: function PDFObjects_get(objId, callback) {
  9219. // If there is a callback, then the get can be async and the object is
  9220. // not required to be resolved right now
  9221. if (callback) {
  9222. this.ensureObj(objId).capability.promise.then(callback);
  9223. return null;
  9224. }
  9225. // If there isn't a callback, the user expects to get the resolved data
  9226. // directly.
  9227. var obj = this.objs[objId];
  9228. // If there isn't an object yet or the object isn't resolved, then the
  9229. // data isn't ready yet!
  9230. if (!obj || !obj.resolved) {
  9231. error('Requesting object that isn\'t resolved yet ' + objId);
  9232. }
  9233. return obj.data;
  9234. },
  9235. /**
  9236. * Resolves the object `objId` with optional `data`.
  9237. */
  9238. resolve: function PDFObjects_resolve(objId, data) {
  9239. var obj = this.ensureObj(objId);
  9240. obj.resolved = true;
  9241. obj.data = data;
  9242. obj.capability.resolve(data);
  9243. },
  9244. isResolved: function PDFObjects_isResolved(objId) {
  9245. var objs = this.objs;
  9246. if (!objs[objId]) {
  9247. return false;
  9248. } else {
  9249. return objs[objId].resolved;
  9250. }
  9251. },
  9252. hasData: function PDFObjects_hasData(objId) {
  9253. return this.isResolved(objId);
  9254. },
  9255. /**
  9256. * Returns the data of `objId` if object exists, null otherwise.
  9257. */
  9258. getData: function PDFObjects_getData(objId) {
  9259. var objs = this.objs;
  9260. if (!objs[objId] || !objs[objId].resolved) {
  9261. return null;
  9262. } else {
  9263. return objs[objId].data;
  9264. }
  9265. },
  9266. clear: function PDFObjects_clear() {
  9267. this.objs = Object.create(null);
  9268. }
  9269. };
  9270. return PDFObjects;
  9271. })();
  9272. /**
  9273. * Allows controlling of the rendering tasks.
  9274. * @class
  9275. * @alias RenderTask
  9276. */
  9277. var RenderTask = (function RenderTaskClosure() {
  9278. function RenderTask(internalRenderTask) {
  9279. this._internalRenderTask = internalRenderTask;
  9280. /**
  9281. * Callback for incremental rendering -- a function that will be called
  9282. * each time the rendering is paused. To continue rendering call the
  9283. * function that is the first argument to the callback.
  9284. * @type {function}
  9285. */
  9286. this.onContinue = null;
  9287. }
  9288. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9289. /**
  9290. * Promise for rendering task completion.
  9291. * @return {Promise}
  9292. */
  9293. get promise() {
  9294. return this._internalRenderTask.capability.promise;
  9295. },
  9296. /**
  9297. * Cancels the rendering task. If the task is currently rendering it will
  9298. * not be cancelled until graphics pauses with a timeout. The promise that
  9299. * this object extends will resolved when cancelled.
  9300. */
  9301. cancel: function RenderTask_cancel() {
  9302. this._internalRenderTask.cancel();
  9303. },
  9304. /**
  9305. * Registers callbacks to indicate the rendering task completion.
  9306. *
  9307. * @param {function} onFulfilled The callback for the rendering completion.
  9308. * @param {function} onRejected The callback for the rendering failure.
  9309. * @return {Promise} A promise that is resolved after the onFulfilled or
  9310. * onRejected callback.
  9311. */
  9312. then: function RenderTask_then(onFulfilled, onRejected) {
  9313. return this.promise.then.apply(this.promise, arguments);
  9314. }
  9315. };
  9316. return RenderTask;
  9317. })();
  9318. /**
  9319. * For internal use only.
  9320. * @ignore
  9321. */
  9322. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9323. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9324. pageNumber) {
  9325. this.callback = callback;
  9326. this.params = params;
  9327. this.objs = objs;
  9328. this.commonObjs = commonObjs;
  9329. this.operatorListIdx = null;
  9330. this.operatorList = operatorList;
  9331. this.pageNumber = pageNumber;
  9332. this.running = false;
  9333. this.graphicsReadyCallback = null;
  9334. this.graphicsReady = false;
  9335. this.useRequestAnimationFrame = false;
  9336. this.cancelled = false;
  9337. this.capability = createPromiseCapability();
  9338. this.task = new RenderTask(this);
  9339. // caching this-bound methods
  9340. this._continueBound = this._continue.bind(this);
  9341. this._scheduleNextBound = this._scheduleNext.bind(this);
  9342. this._nextBound = this._next.bind(this);
  9343. }
  9344. InternalRenderTask.prototype = {
  9345. initalizeGraphics:
  9346. function InternalRenderTask_initalizeGraphics(transparency) {
  9347. if (this.cancelled) {
  9348. return;
  9349. }
  9350. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  9351. globalScope.StepperManager.enabled) {
  9352. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9353. this.stepper.init(this.operatorList);
  9354. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9355. }
  9356. var params = this.params;
  9357. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9358. this.objs, params.imageLayer);
  9359. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9360. this.operatorListIdx = 0;
  9361. this.graphicsReady = true;
  9362. if (this.graphicsReadyCallback) {
  9363. this.graphicsReadyCallback();
  9364. }
  9365. },
  9366. cancel: function InternalRenderTask_cancel() {
  9367. this.running = false;
  9368. this.cancelled = true;
  9369. this.callback('cancelled');
  9370. },
  9371. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9372. if (!this.graphicsReady) {
  9373. if (!this.graphicsReadyCallback) {
  9374. this.graphicsReadyCallback = this._continueBound;
  9375. }
  9376. return;
  9377. }
  9378. if (this.stepper) {
  9379. this.stepper.updateOperatorList(this.operatorList);
  9380. }
  9381. if (this.running) {
  9382. return;
  9383. }
  9384. this._continue();
  9385. },
  9386. _continue: function InternalRenderTask__continue() {
  9387. this.running = true;
  9388. if (this.cancelled) {
  9389. return;
  9390. }
  9391. if (this.task.onContinue) {
  9392. this.task.onContinue.call(this.task, this._scheduleNextBound);
  9393. } else {
  9394. this._scheduleNext();
  9395. }
  9396. },
  9397. _scheduleNext: function InternalRenderTask__scheduleNext() {
  9398. if (this.useRequestAnimationFrame) {
  9399. window.requestAnimationFrame(this._nextBound);
  9400. } else {
  9401. Promise.resolve(undefined).then(this._nextBound);
  9402. }
  9403. },
  9404. _next: function InternalRenderTask__next() {
  9405. if (this.cancelled) {
  9406. return;
  9407. }
  9408. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  9409. this.operatorListIdx,
  9410. this._continueBound,
  9411. this.stepper);
  9412. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  9413. this.running = false;
  9414. if (this.operatorList.lastChunk) {
  9415. this.gfx.endDrawing();
  9416. this.callback();
  9417. }
  9418. }
  9419. }
  9420. };
  9421. return InternalRenderTask;
  9422. })();
  9423. /**
  9424. * (Deprecated) Global observer of unsupported feature usages. Use
  9425. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  9426. */
  9427. PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() {
  9428. var listeners = [];
  9429. return {
  9430. listen: function (cb) {
  9431. deprecated('Global UnsupportedManager.listen is used: ' +
  9432. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  9433. listeners.push(cb);
  9434. },
  9435. notify: function (featureId) {
  9436. for (var i = 0, ii = listeners.length; i < ii; i++) {
  9437. listeners[i](featureId);
  9438. }
  9439. }
  9440. };
  9441. })();
  9442. exports.getDocument = PDFJS.getDocument;
  9443. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  9444. exports.PDFDocumentProxy = PDFDocumentProxy;
  9445. exports.PDFPageProxy = PDFPageProxy;
  9446. }));
  9447. }).call(pdfjsLibs);
  9448. exports.PDFJS = pdfjsLibs.pdfjsSharedGlobal.PDFJS;
  9449. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  9450. exports.PDFDataRangeTransport =
  9451. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  9452. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  9453. exports.AnnotationLayer =
  9454. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  9455. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  9456. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  9457. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  9458. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  9459. exports.UnexpectedResponseException =
  9460. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  9461. }));