pdf.js 207 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. /* globals PDFJS */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. PDFJS.version = '1.0.635';
  24. PDFJS.build = '5e18614';
  25. (function pdfjsWrapper() {
  26. // Use strict in our context only - users might not want it
  27. 'use strict';
  28. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  29. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  30. /* Copyright 2012 Mozilla Foundation
  31. *
  32. * Licensed under the Apache License, Version 2.0 (the "License");
  33. * you may not use this file except in compliance with the License.
  34. * You may obtain a copy of the License at
  35. *
  36. * http://www.apache.org/licenses/LICENSE-2.0
  37. *
  38. * Unless required by applicable law or agreed to in writing, software
  39. * distributed under the License is distributed on an "AS IS" BASIS,
  40. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41. * See the License for the specific language governing permissions and
  42. * limitations under the License.
  43. */
  44. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  45. Promise */
  46. 'use strict';
  47. var globalScope = (typeof window === 'undefined') ? this : window;
  48. var isWorker = (typeof window === 'undefined');
  49. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  50. var TextRenderingMode = {
  51. FILL: 0,
  52. STROKE: 1,
  53. FILL_STROKE: 2,
  54. INVISIBLE: 3,
  55. FILL_ADD_TO_PATH: 4,
  56. STROKE_ADD_TO_PATH: 5,
  57. FILL_STROKE_ADD_TO_PATH: 6,
  58. ADD_TO_PATH: 7,
  59. FILL_STROKE_MASK: 3,
  60. ADD_TO_PATH_FLAG: 4
  61. };
  62. var ImageKind = {
  63. GRAYSCALE_1BPP: 1,
  64. RGB_24BPP: 2,
  65. RGBA_32BPP: 3
  66. };
  67. var AnnotationType = {
  68. WIDGET: 1,
  69. TEXT: 2,
  70. LINK: 3
  71. };
  72. var StreamType = {
  73. UNKNOWN: 0,
  74. FLATE: 1,
  75. LZW: 2,
  76. DCT: 3,
  77. JPX: 4,
  78. JBIG: 5,
  79. A85: 6,
  80. AHX: 7,
  81. CCF: 8,
  82. RL: 9
  83. };
  84. var FontType = {
  85. UNKNOWN: 0,
  86. TYPE1: 1,
  87. TYPE1C: 2,
  88. CIDFONTTYPE0: 3,
  89. CIDFONTTYPE0C: 4,
  90. TRUETYPE: 5,
  91. CIDFONTTYPE2: 6,
  92. TYPE3: 7,
  93. OPENTYPE: 8,
  94. TYPE0: 9,
  95. MMTYPE1: 10
  96. };
  97. // The global PDFJS object exposes the API
  98. // In production, it will be declared outside a global wrapper
  99. // In development, it will be declared here
  100. if (!globalScope.PDFJS) {
  101. globalScope.PDFJS = {};
  102. }
  103. globalScope.PDFJS.pdfBug = false;
  104. PDFJS.VERBOSITY_LEVELS = {
  105. errors: 0,
  106. warnings: 1,
  107. infos: 5
  108. };
  109. // All the possible operations for an operator list.
  110. var OPS = PDFJS.OPS = {
  111. // Intentionally start from 1 so it is easy to spot bad operators that will be
  112. // 0's.
  113. dependency: 1,
  114. setLineWidth: 2,
  115. setLineCap: 3,
  116. setLineJoin: 4,
  117. setMiterLimit: 5,
  118. setDash: 6,
  119. setRenderingIntent: 7,
  120. setFlatness: 8,
  121. setGState: 9,
  122. save: 10,
  123. restore: 11,
  124. transform: 12,
  125. moveTo: 13,
  126. lineTo: 14,
  127. curveTo: 15,
  128. curveTo2: 16,
  129. curveTo3: 17,
  130. closePath: 18,
  131. rectangle: 19,
  132. stroke: 20,
  133. closeStroke: 21,
  134. fill: 22,
  135. eoFill: 23,
  136. fillStroke: 24,
  137. eoFillStroke: 25,
  138. closeFillStroke: 26,
  139. closeEOFillStroke: 27,
  140. endPath: 28,
  141. clip: 29,
  142. eoClip: 30,
  143. beginText: 31,
  144. endText: 32,
  145. setCharSpacing: 33,
  146. setWordSpacing: 34,
  147. setHScale: 35,
  148. setLeading: 36,
  149. setFont: 37,
  150. setTextRenderingMode: 38,
  151. setTextRise: 39,
  152. moveText: 40,
  153. setLeadingMoveText: 41,
  154. setTextMatrix: 42,
  155. nextLine: 43,
  156. showText: 44,
  157. showSpacedText: 45,
  158. nextLineShowText: 46,
  159. nextLineSetSpacingShowText: 47,
  160. setCharWidth: 48,
  161. setCharWidthAndBounds: 49,
  162. setStrokeColorSpace: 50,
  163. setFillColorSpace: 51,
  164. setStrokeColor: 52,
  165. setStrokeColorN: 53,
  166. setFillColor: 54,
  167. setFillColorN: 55,
  168. setStrokeGray: 56,
  169. setFillGray: 57,
  170. setStrokeRGBColor: 58,
  171. setFillRGBColor: 59,
  172. setStrokeCMYKColor: 60,
  173. setFillCMYKColor: 61,
  174. shadingFill: 62,
  175. beginInlineImage: 63,
  176. beginImageData: 64,
  177. endInlineImage: 65,
  178. paintXObject: 66,
  179. markPoint: 67,
  180. markPointProps: 68,
  181. beginMarkedContent: 69,
  182. beginMarkedContentProps: 70,
  183. endMarkedContent: 71,
  184. beginCompat: 72,
  185. endCompat: 73,
  186. paintFormXObjectBegin: 74,
  187. paintFormXObjectEnd: 75,
  188. beginGroup: 76,
  189. endGroup: 77,
  190. beginAnnotations: 78,
  191. endAnnotations: 79,
  192. beginAnnotation: 80,
  193. endAnnotation: 81,
  194. paintJpegXObject: 82,
  195. paintImageMaskXObject: 83,
  196. paintImageMaskXObjectGroup: 84,
  197. paintImageXObject: 85,
  198. paintInlineImageXObject: 86,
  199. paintInlineImageXObjectGroup: 87,
  200. paintImageXObjectRepeat: 88,
  201. paintImageMaskXObjectRepeat: 89,
  202. paintSolidColorImageMask: 90,
  203. constructPath: 91
  204. };
  205. // A notice for devs. These are good for things that are helpful to devs, such
  206. // as warning that Workers were disabled, which is important to devs but not
  207. // end users.
  208. function info(msg) {
  209. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  210. console.log('Info: ' + msg);
  211. }
  212. }
  213. // Non-fatal warnings.
  214. function warn(msg) {
  215. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  216. console.log('Warning: ' + msg);
  217. }
  218. }
  219. // Fatal errors that should trigger the fallback UI and halt execution by
  220. // throwing an exception.
  221. function error(msg) {
  222. // If multiple arguments were passed, pass them all to the log function.
  223. if (arguments.length > 1) {
  224. var logArguments = ['Error:'];
  225. logArguments.push.apply(logArguments, arguments);
  226. console.log.apply(console, logArguments);
  227. // Join the arguments into a single string for the lines below.
  228. msg = [].join.call(arguments, ' ');
  229. } else {
  230. console.log('Error: ' + msg);
  231. }
  232. console.log(backtrace());
  233. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  234. throw new Error(msg);
  235. }
  236. function backtrace() {
  237. try {
  238. throw new Error();
  239. } catch (e) {
  240. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  241. }
  242. }
  243. function assert(cond, msg) {
  244. if (!cond) {
  245. error(msg);
  246. }
  247. }
  248. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  249. unknown: 'unknown',
  250. forms: 'forms',
  251. javaScript: 'javaScript',
  252. smask: 'smask',
  253. shadingPattern: 'shadingPattern',
  254. font: 'font'
  255. };
  256. var UnsupportedManager = PDFJS.UnsupportedManager =
  257. (function UnsupportedManagerClosure() {
  258. var listeners = [];
  259. return {
  260. listen: function (cb) {
  261. listeners.push(cb);
  262. },
  263. notify: function (featureId) {
  264. warn('Unsupported feature "' + featureId + '"');
  265. for (var i = 0, ii = listeners.length; i < ii; i++) {
  266. listeners[i](featureId);
  267. }
  268. }
  269. };
  270. })();
  271. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  272. // absolute URL, it will be returned as is.
  273. function combineUrl(baseUrl, url) {
  274. if (!url) {
  275. return baseUrl;
  276. }
  277. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  278. return url;
  279. }
  280. var i;
  281. if (url.charAt(0) === '/') {
  282. // absolute path
  283. i = baseUrl.indexOf('://');
  284. if (url.charAt(1) === '/') {
  285. ++i;
  286. } else {
  287. i = baseUrl.indexOf('/', i + 3);
  288. }
  289. return baseUrl.substring(0, i) + url;
  290. } else {
  291. // relative path
  292. var pathLength = baseUrl.length;
  293. i = baseUrl.lastIndexOf('#');
  294. pathLength = i >= 0 ? i : pathLength;
  295. i = baseUrl.lastIndexOf('?', pathLength);
  296. pathLength = i >= 0 ? i : pathLength;
  297. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  298. return baseUrl.substring(0, prefixLength + 1) + url;
  299. }
  300. }
  301. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  302. function isValidUrl(url, allowRelative) {
  303. if (!url) {
  304. return false;
  305. }
  306. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  307. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  308. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  309. if (!protocol) {
  310. return allowRelative;
  311. }
  312. protocol = protocol[0].toLowerCase();
  313. switch (protocol) {
  314. case 'http':
  315. case 'https':
  316. case 'ftp':
  317. case 'mailto':
  318. return true;
  319. default:
  320. return false;
  321. }
  322. }
  323. PDFJS.isValidUrl = isValidUrl;
  324. function shadow(obj, prop, value) {
  325. Object.defineProperty(obj, prop, { value: value,
  326. enumerable: true,
  327. configurable: true,
  328. writable: false });
  329. return value;
  330. }
  331. var PasswordResponses = PDFJS.PasswordResponses = {
  332. NEED_PASSWORD: 1,
  333. INCORRECT_PASSWORD: 2
  334. };
  335. var PasswordException = (function PasswordExceptionClosure() {
  336. function PasswordException(msg, code) {
  337. this.name = 'PasswordException';
  338. this.message = msg;
  339. this.code = code;
  340. }
  341. PasswordException.prototype = new Error();
  342. PasswordException.constructor = PasswordException;
  343. return PasswordException;
  344. })();
  345. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  346. function UnknownErrorException(msg, details) {
  347. this.name = 'UnknownErrorException';
  348. this.message = msg;
  349. this.details = details;
  350. }
  351. UnknownErrorException.prototype = new Error();
  352. UnknownErrorException.constructor = UnknownErrorException;
  353. return UnknownErrorException;
  354. })();
  355. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  356. function InvalidPDFException(msg) {
  357. this.name = 'InvalidPDFException';
  358. this.message = msg;
  359. }
  360. InvalidPDFException.prototype = new Error();
  361. InvalidPDFException.constructor = InvalidPDFException;
  362. return InvalidPDFException;
  363. })();
  364. var MissingPDFException = (function MissingPDFExceptionClosure() {
  365. function MissingPDFException(msg) {
  366. this.name = 'MissingPDFException';
  367. this.message = msg;
  368. }
  369. MissingPDFException.prototype = new Error();
  370. MissingPDFException.constructor = MissingPDFException;
  371. return MissingPDFException;
  372. })();
  373. var NotImplementedException = (function NotImplementedExceptionClosure() {
  374. function NotImplementedException(msg) {
  375. this.message = msg;
  376. }
  377. NotImplementedException.prototype = new Error();
  378. NotImplementedException.prototype.name = 'NotImplementedException';
  379. NotImplementedException.constructor = NotImplementedException;
  380. return NotImplementedException;
  381. })();
  382. var MissingDataException = (function MissingDataExceptionClosure() {
  383. function MissingDataException(begin, end) {
  384. this.begin = begin;
  385. this.end = end;
  386. this.message = 'Missing data [' + begin + ', ' + end + ')';
  387. }
  388. MissingDataException.prototype = new Error();
  389. MissingDataException.prototype.name = 'MissingDataException';
  390. MissingDataException.constructor = MissingDataException;
  391. return MissingDataException;
  392. })();
  393. var XRefParseException = (function XRefParseExceptionClosure() {
  394. function XRefParseException(msg) {
  395. this.message = msg;
  396. }
  397. XRefParseException.prototype = new Error();
  398. XRefParseException.prototype.name = 'XRefParseException';
  399. XRefParseException.constructor = XRefParseException;
  400. return XRefParseException;
  401. })();
  402. function bytesToString(bytes) {
  403. var length = bytes.length;
  404. var MAX_ARGUMENT_COUNT = 8192;
  405. if (length < MAX_ARGUMENT_COUNT) {
  406. return String.fromCharCode.apply(null, bytes);
  407. }
  408. var strBuf = [];
  409. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  410. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  411. var chunk = bytes.subarray(i, chunkEnd);
  412. strBuf.push(String.fromCharCode.apply(null, chunk));
  413. }
  414. return strBuf.join('');
  415. }
  416. function stringToArray(str) {
  417. var length = str.length;
  418. var array = new Uint16Array(length);
  419. for (var i = 0; i < length; ++i) {
  420. array[i] = str.charCodeAt(i);
  421. }
  422. return array;
  423. }
  424. function stringToBytes(str) {
  425. var length = str.length;
  426. var bytes = new Uint8Array(length);
  427. for (var i = 0; i < length; ++i) {
  428. bytes[i] = str.charCodeAt(i) & 0xFF;
  429. }
  430. return bytes;
  431. }
  432. function string32(value) {
  433. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  434. (value >> 8) & 0xff, value & 0xff);
  435. }
  436. function log2(x) {
  437. var n = 1, i = 0;
  438. while (x > n) {
  439. n <<= 1;
  440. i++;
  441. }
  442. return i;
  443. }
  444. function readInt8(data, start) {
  445. return (data[start] << 24) >> 24;
  446. }
  447. function readUint16(data, offset) {
  448. return (data[offset] << 8) | data[offset + 1];
  449. }
  450. function readUint32(data, offset) {
  451. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  452. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  453. }
  454. // Lazy test the endianness of the platform
  455. // NOTE: This will be 'true' for simulated TypedArrays
  456. function isLittleEndian() {
  457. var buffer8 = new Uint8Array(2);
  458. buffer8[0] = 1;
  459. var buffer16 = new Uint16Array(buffer8.buffer);
  460. return (buffer16[0] === 1);
  461. }
  462. Object.defineProperty(PDFJS, 'isLittleEndian', {
  463. configurable: true,
  464. get: function PDFJS_isLittleEndian() {
  465. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  466. }
  467. });
  468. // Lazy test if the userAgant support CanvasTypedArrays
  469. function hasCanvasTypedArrays() {
  470. var canvas = document.createElement('canvas');
  471. canvas.width = canvas.height = 1;
  472. var ctx = canvas.getContext('2d');
  473. var imageData = ctx.createImageData(1, 1);
  474. return (typeof imageData.data.buffer !== 'undefined');
  475. }
  476. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  477. configurable: true,
  478. get: function PDFJS_hasCanvasTypedArrays() {
  479. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  480. }
  481. });
  482. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  483. function Uint32ArrayView(buffer, length) {
  484. this.buffer = buffer;
  485. this.byteLength = buffer.length;
  486. this.length = length === undefined ? (this.byteLength >> 2) : length;
  487. ensureUint32ArrayViewProps(this.length);
  488. }
  489. Uint32ArrayView.prototype = Object.create(null);
  490. var uint32ArrayViewSetters = 0;
  491. function createUint32ArrayProp(index) {
  492. return {
  493. get: function () {
  494. var buffer = this.buffer, offset = index << 2;
  495. return (buffer[offset] | (buffer[offset + 1] << 8) |
  496. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  497. },
  498. set: function (value) {
  499. var buffer = this.buffer, offset = index << 2;
  500. buffer[offset] = value & 255;
  501. buffer[offset + 1] = (value >> 8) & 255;
  502. buffer[offset + 2] = (value >> 16) & 255;
  503. buffer[offset + 3] = (value >>> 24) & 255;
  504. }
  505. };
  506. }
  507. function ensureUint32ArrayViewProps(length) {
  508. while (uint32ArrayViewSetters < length) {
  509. Object.defineProperty(Uint32ArrayView.prototype,
  510. uint32ArrayViewSetters,
  511. createUint32ArrayProp(uint32ArrayViewSetters));
  512. uint32ArrayViewSetters++;
  513. }
  514. }
  515. return Uint32ArrayView;
  516. })();
  517. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  518. var Util = PDFJS.Util = (function UtilClosure() {
  519. function Util() {}
  520. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  521. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  522. // creating many intermediate strings.
  523. Util.makeCssRgb = function Util_makeCssRgb(rgb) {
  524. rgbBuf[1] = rgb[0];
  525. rgbBuf[3] = rgb[1];
  526. rgbBuf[5] = rgb[2];
  527. return rgbBuf.join('');
  528. };
  529. // Concatenates two transformation matrices together and returns the result.
  530. Util.transform = function Util_transform(m1, m2) {
  531. return [
  532. m1[0] * m2[0] + m1[2] * m2[1],
  533. m1[1] * m2[0] + m1[3] * m2[1],
  534. m1[0] * m2[2] + m1[2] * m2[3],
  535. m1[1] * m2[2] + m1[3] * m2[3],
  536. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  537. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  538. ];
  539. };
  540. // For 2d affine transforms
  541. Util.applyTransform = function Util_applyTransform(p, m) {
  542. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  543. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  544. return [xt, yt];
  545. };
  546. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  547. var d = m[0] * m[3] - m[1] * m[2];
  548. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  549. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  550. return [xt, yt];
  551. };
  552. // Applies the transform to the rectangle and finds the minimum axially
  553. // aligned bounding box.
  554. Util.getAxialAlignedBoundingBox =
  555. function Util_getAxialAlignedBoundingBox(r, m) {
  556. var p1 = Util.applyTransform(r, m);
  557. var p2 = Util.applyTransform(r.slice(2, 4), m);
  558. var p3 = Util.applyTransform([r[0], r[3]], m);
  559. var p4 = Util.applyTransform([r[2], r[1]], m);
  560. return [
  561. Math.min(p1[0], p2[0], p3[0], p4[0]),
  562. Math.min(p1[1], p2[1], p3[1], p4[1]),
  563. Math.max(p1[0], p2[0], p3[0], p4[0]),
  564. Math.max(p1[1], p2[1], p3[1], p4[1])
  565. ];
  566. };
  567. Util.inverseTransform = function Util_inverseTransform(m) {
  568. var d = m[0] * m[3] - m[1] * m[2];
  569. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  570. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  571. };
  572. // Apply a generic 3d matrix M on a 3-vector v:
  573. // | a b c | | X |
  574. // | d e f | x | Y |
  575. // | g h i | | Z |
  576. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  577. // with v as [X,Y,Z]
  578. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  579. return [
  580. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  581. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  582. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  583. ];
  584. };
  585. // This calculation uses Singular Value Decomposition.
  586. // The SVD can be represented with formula A = USV. We are interested in the
  587. // matrix S here because it represents the scale values.
  588. Util.singularValueDecompose2dScale =
  589. function Util_singularValueDecompose2dScale(m) {
  590. var transpose = [m[0], m[2], m[1], m[3]];
  591. // Multiply matrix m with its transpose.
  592. var a = m[0] * transpose[0] + m[1] * transpose[2];
  593. var b = m[0] * transpose[1] + m[1] * transpose[3];
  594. var c = m[2] * transpose[0] + m[3] * transpose[2];
  595. var d = m[2] * transpose[1] + m[3] * transpose[3];
  596. // Solve the second degree polynomial to get roots.
  597. var first = (a + d) / 2;
  598. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  599. var sx = first + second || 1;
  600. var sy = first - second || 1;
  601. // Scale values are the square roots of the eigenvalues.
  602. return [Math.sqrt(sx), Math.sqrt(sy)];
  603. };
  604. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  605. // For coordinate systems whose origin lies in the bottom-left, this
  606. // means normalization to (BL,TR) ordering. For systems with origin in the
  607. // top-left, this means (TL,BR) ordering.
  608. Util.normalizeRect = function Util_normalizeRect(rect) {
  609. var r = rect.slice(0); // clone rect
  610. if (rect[0] > rect[2]) {
  611. r[0] = rect[2];
  612. r[2] = rect[0];
  613. }
  614. if (rect[1] > rect[3]) {
  615. r[1] = rect[3];
  616. r[3] = rect[1];
  617. }
  618. return r;
  619. };
  620. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  621. // intersection of rect1 and rect2. If no intersection, returns 'false'
  622. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  623. Util.intersect = function Util_intersect(rect1, rect2) {
  624. function compare(a, b) {
  625. return a - b;
  626. }
  627. // Order points along the axes
  628. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  629. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  630. result = [];
  631. rect1 = Util.normalizeRect(rect1);
  632. rect2 = Util.normalizeRect(rect2);
  633. // X: first and second points belong to different rectangles?
  634. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  635. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  636. // Intersection must be between second and third points
  637. result[0] = orderedX[1];
  638. result[2] = orderedX[2];
  639. } else {
  640. return false;
  641. }
  642. // Y: first and second points belong to different rectangles?
  643. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  644. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  645. // Intersection must be between second and third points
  646. result[1] = orderedY[1];
  647. result[3] = orderedY[2];
  648. } else {
  649. return false;
  650. }
  651. return result;
  652. };
  653. Util.sign = function Util_sign(num) {
  654. return num < 0 ? -1 : 1;
  655. };
  656. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  657. Array.prototype.push.apply(arr1, arr2);
  658. };
  659. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  660. Array.prototype.unshift.apply(arr1, arr2);
  661. };
  662. Util.extendObj = function extendObj(obj1, obj2) {
  663. for (var key in obj2) {
  664. obj1[key] = obj2[key];
  665. }
  666. };
  667. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  668. name) {
  669. while (dict && !dict.has(name)) {
  670. dict = dict.get('Parent');
  671. }
  672. if (!dict) {
  673. return null;
  674. }
  675. return dict.get(name);
  676. };
  677. Util.inherit = function Util_inherit(sub, base, prototype) {
  678. sub.prototype = Object.create(base.prototype);
  679. sub.prototype.constructor = sub;
  680. for (var prop in prototype) {
  681. sub.prototype[prop] = prototype[prop];
  682. }
  683. };
  684. Util.loadScript = function Util_loadScript(src, callback) {
  685. var script = document.createElement('script');
  686. var loaded = false;
  687. script.setAttribute('src', src);
  688. if (callback) {
  689. script.onload = function() {
  690. if (!loaded) {
  691. callback();
  692. }
  693. loaded = true;
  694. };
  695. }
  696. document.getElementsByTagName('head')[0].appendChild(script);
  697. };
  698. return Util;
  699. })();
  700. /**
  701. * PDF page viewport created based on scale, rotation and offset.
  702. * @class
  703. * @alias PDFJS.PageViewport
  704. */
  705. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  706. /**
  707. * @constructor
  708. * @private
  709. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  710. * @param scale {number} scale of the viewport.
  711. * @param rotation {number} rotations of the viewport in degrees.
  712. * @param offsetX {number} offset X
  713. * @param offsetY {number} offset Y
  714. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  715. */
  716. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  717. this.viewBox = viewBox;
  718. this.scale = scale;
  719. this.rotation = rotation;
  720. this.offsetX = offsetX;
  721. this.offsetY = offsetY;
  722. // creating transform to convert pdf coordinate system to the normal
  723. // canvas like coordinates taking in account scale and rotation
  724. var centerX = (viewBox[2] + viewBox[0]) / 2;
  725. var centerY = (viewBox[3] + viewBox[1]) / 2;
  726. var rotateA, rotateB, rotateC, rotateD;
  727. rotation = rotation % 360;
  728. rotation = rotation < 0 ? rotation + 360 : rotation;
  729. switch (rotation) {
  730. case 180:
  731. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  732. break;
  733. case 90:
  734. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  735. break;
  736. case 270:
  737. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  738. break;
  739. //case 0:
  740. default:
  741. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  742. break;
  743. }
  744. if (dontFlip) {
  745. rotateC = -rotateC; rotateD = -rotateD;
  746. }
  747. var offsetCanvasX, offsetCanvasY;
  748. var width, height;
  749. if (rotateA === 0) {
  750. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  751. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  752. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  753. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  754. } else {
  755. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  756. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  757. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  758. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  759. }
  760. // creating transform for the following operations:
  761. // translate(-centerX, -centerY), rotate and flip vertically,
  762. // scale, and translate(offsetCanvasX, offsetCanvasY)
  763. this.transform = [
  764. rotateA * scale,
  765. rotateB * scale,
  766. rotateC * scale,
  767. rotateD * scale,
  768. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  769. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  770. ];
  771. this.width = width;
  772. this.height = height;
  773. this.fontScale = scale;
  774. }
  775. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  776. /**
  777. * Clones viewport with additional properties.
  778. * @param args {Object} (optional) If specified, may contain the 'scale' or
  779. * 'rotation' properties to override the corresponding properties in
  780. * the cloned viewport.
  781. * @returns {PDFJS.PageViewport} Cloned viewport.
  782. */
  783. clone: function PageViewPort_clone(args) {
  784. args = args || {};
  785. var scale = 'scale' in args ? args.scale : this.scale;
  786. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  787. return new PageViewport(this.viewBox.slice(), scale, rotation,
  788. this.offsetX, this.offsetY, args.dontFlip);
  789. },
  790. /**
  791. * Converts PDF point to the viewport coordinates. For examples, useful for
  792. * converting PDF location into canvas pixel coordinates.
  793. * @param x {number} X coordinate.
  794. * @param y {number} Y coordinate.
  795. * @returns {Object} Object that contains 'x' and 'y' properties of the
  796. * point in the viewport coordinate space.
  797. * @see {@link convertToPdfPoint}
  798. * @see {@link convertToViewportRectangle}
  799. */
  800. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  801. return Util.applyTransform([x, y], this.transform);
  802. },
  803. /**
  804. * Converts PDF rectangle to the viewport coordinates.
  805. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  806. * @returns {Array} Contains corresponding coordinates of the rectangle
  807. * in the viewport coordinate space.
  808. * @see {@link convertToViewportPoint}
  809. */
  810. convertToViewportRectangle:
  811. function PageViewport_convertToViewportRectangle(rect) {
  812. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  813. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  814. return [tl[0], tl[1], br[0], br[1]];
  815. },
  816. /**
  817. * Converts viewport coordinates to the PDF location. For examples, useful
  818. * for converting canvas pixel location into PDF one.
  819. * @param x {number} X coordinate.
  820. * @param y {number} Y coordinate.
  821. * @returns {Object} Object that contains 'x' and 'y' properties of the
  822. * point in the PDF coordinate space.
  823. * @see {@link convertToViewportPoint}
  824. */
  825. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  826. return Util.applyInverseTransform([x, y], this.transform);
  827. }
  828. };
  829. return PageViewport;
  830. })();
  831. var PDFStringTranslateTable = [
  832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  833. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  834. 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,
  835. 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,
  836. 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,
  837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  838. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  839. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  840. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  841. ];
  842. function stringToPDFString(str) {
  843. var i, n = str.length, strBuf = [];
  844. if (str[0] === '\xFE' && str[1] === '\xFF') {
  845. // UTF16BE BOM
  846. for (i = 2; i < n; i += 2) {
  847. strBuf.push(String.fromCharCode(
  848. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  849. }
  850. } else {
  851. for (i = 0; i < n; ++i) {
  852. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  853. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  854. }
  855. }
  856. return strBuf.join('');
  857. }
  858. function stringToUTF8String(str) {
  859. return decodeURIComponent(escape(str));
  860. }
  861. function isEmptyObj(obj) {
  862. for (var key in obj) {
  863. return false;
  864. }
  865. return true;
  866. }
  867. function isBool(v) {
  868. return typeof v === 'boolean';
  869. }
  870. function isInt(v) {
  871. return typeof v === 'number' && ((v | 0) === v);
  872. }
  873. function isNum(v) {
  874. return typeof v === 'number';
  875. }
  876. function isString(v) {
  877. return typeof v === 'string';
  878. }
  879. function isNull(v) {
  880. return v === null;
  881. }
  882. function isName(v) {
  883. return v instanceof Name;
  884. }
  885. function isCmd(v, cmd) {
  886. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  887. }
  888. function isDict(v, type) {
  889. if (!(v instanceof Dict)) {
  890. return false;
  891. }
  892. if (!type) {
  893. return true;
  894. }
  895. var dictType = v.get('Type');
  896. return isName(dictType) && dictType.name === type;
  897. }
  898. function isArray(v) {
  899. return v instanceof Array;
  900. }
  901. function isStream(v) {
  902. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  903. }
  904. function isArrayBuffer(v) {
  905. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  906. }
  907. function isRef(v) {
  908. return v instanceof Ref;
  909. }
  910. /**
  911. * Promise Capability object.
  912. *
  913. * @typedef {Object} PromiseCapability
  914. * @property {Promise} promise - A promise object.
  915. * @property {function} resolve - Fullfills the promise.
  916. * @property {function} reject - Rejects the promise.
  917. */
  918. /**
  919. * Creates a promise capability object.
  920. * @alias PDFJS.createPromiseCapability
  921. *
  922. * @return {PromiseCapability} A capability object contains:
  923. * - a Promise, resolve and reject methods.
  924. */
  925. function createPromiseCapability() {
  926. var capability = {};
  927. capability.promise = new Promise(function (resolve, reject) {
  928. capability.resolve = resolve;
  929. capability.reject = reject;
  930. });
  931. return capability;
  932. }
  933. PDFJS.createPromiseCapability = createPromiseCapability;
  934. /**
  935. * Polyfill for Promises:
  936. * The following promise implementation tries to generally implement the
  937. * Promise/A+ spec. Some notable differences from other promise libaries are:
  938. * - There currently isn't a seperate deferred and promise object.
  939. * - Unhandled rejections eventually show an error if they aren't handled.
  940. *
  941. * Based off of the work in:
  942. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  943. */
  944. (function PromiseClosure() {
  945. if (globalScope.Promise) {
  946. // Promises existing in the DOM/Worker, checking presence of all/resolve
  947. if (typeof globalScope.Promise.all !== 'function') {
  948. globalScope.Promise.all = function (iterable) {
  949. var count = 0, results = [], resolve, reject;
  950. var promise = new globalScope.Promise(function (resolve_, reject_) {
  951. resolve = resolve_;
  952. reject = reject_;
  953. });
  954. iterable.forEach(function (p, i) {
  955. count++;
  956. p.then(function (result) {
  957. results[i] = result;
  958. count--;
  959. if (count === 0) {
  960. resolve(results);
  961. }
  962. }, reject);
  963. });
  964. if (count === 0) {
  965. resolve(results);
  966. }
  967. return promise;
  968. };
  969. }
  970. if (typeof globalScope.Promise.resolve !== 'function') {
  971. globalScope.Promise.resolve = function (value) {
  972. return new globalScope.Promise(function (resolve) { resolve(value); });
  973. };
  974. }
  975. if (typeof globalScope.Promise.reject !== 'function') {
  976. globalScope.Promise.reject = function (reason) {
  977. return new globalScope.Promise(function (resolve, reject) {
  978. reject(reason);
  979. });
  980. };
  981. }
  982. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  983. globalScope.Promise.prototype.catch = function (onReject) {
  984. return globalScope.Promise.prototype.then(undefined, onReject);
  985. };
  986. }
  987. return;
  988. }
  989. var STATUS_PENDING = 0;
  990. var STATUS_RESOLVED = 1;
  991. var STATUS_REJECTED = 2;
  992. // In an attempt to avoid silent exceptions, unhandled rejections are
  993. // tracked and if they aren't handled in a certain amount of time an
  994. // error is logged.
  995. var REJECTION_TIMEOUT = 500;
  996. var HandlerManager = {
  997. handlers: [],
  998. running: false,
  999. unhandledRejections: [],
  1000. pendingRejectionCheck: false,
  1001. scheduleHandlers: function scheduleHandlers(promise) {
  1002. if (promise._status === STATUS_PENDING) {
  1003. return;
  1004. }
  1005. this.handlers = this.handlers.concat(promise._handlers);
  1006. promise._handlers = [];
  1007. if (this.running) {
  1008. return;
  1009. }
  1010. this.running = true;
  1011. setTimeout(this.runHandlers.bind(this), 0);
  1012. },
  1013. runHandlers: function runHandlers() {
  1014. var RUN_TIMEOUT = 1; // ms
  1015. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1016. while (this.handlers.length > 0) {
  1017. var handler = this.handlers.shift();
  1018. var nextStatus = handler.thisPromise._status;
  1019. var nextValue = handler.thisPromise._value;
  1020. try {
  1021. if (nextStatus === STATUS_RESOLVED) {
  1022. if (typeof handler.onResolve === 'function') {
  1023. nextValue = handler.onResolve(nextValue);
  1024. }
  1025. } else if (typeof handler.onReject === 'function') {
  1026. nextValue = handler.onReject(nextValue);
  1027. nextStatus = STATUS_RESOLVED;
  1028. if (handler.thisPromise._unhandledRejection) {
  1029. this.removeUnhandeledRejection(handler.thisPromise);
  1030. }
  1031. }
  1032. } catch (ex) {
  1033. nextStatus = STATUS_REJECTED;
  1034. nextValue = ex;
  1035. }
  1036. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1037. if (Date.now() >= timeoutAt) {
  1038. break;
  1039. }
  1040. }
  1041. if (this.handlers.length > 0) {
  1042. setTimeout(this.runHandlers.bind(this), 0);
  1043. return;
  1044. }
  1045. this.running = false;
  1046. },
  1047. addUnhandledRejection: function addUnhandledRejection(promise) {
  1048. this.unhandledRejections.push({
  1049. promise: promise,
  1050. time: Date.now()
  1051. });
  1052. this.scheduleRejectionCheck();
  1053. },
  1054. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1055. promise._unhandledRejection = false;
  1056. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1057. if (this.unhandledRejections[i].promise === promise) {
  1058. this.unhandledRejections.splice(i);
  1059. i--;
  1060. }
  1061. }
  1062. },
  1063. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1064. if (this.pendingRejectionCheck) {
  1065. return;
  1066. }
  1067. this.pendingRejectionCheck = true;
  1068. setTimeout(function rejectionCheck() {
  1069. this.pendingRejectionCheck = false;
  1070. var now = Date.now();
  1071. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1072. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1073. var unhandled = this.unhandledRejections[i].promise._value;
  1074. var msg = 'Unhandled rejection: ' + unhandled;
  1075. if (unhandled.stack) {
  1076. msg += '\n' + unhandled.stack;
  1077. }
  1078. warn(msg);
  1079. this.unhandledRejections.splice(i);
  1080. i--;
  1081. }
  1082. }
  1083. if (this.unhandledRejections.length) {
  1084. this.scheduleRejectionCheck();
  1085. }
  1086. }.bind(this), REJECTION_TIMEOUT);
  1087. }
  1088. };
  1089. function Promise(resolver) {
  1090. this._status = STATUS_PENDING;
  1091. this._handlers = [];
  1092. try {
  1093. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1094. } catch (e) {
  1095. this._reject(e);
  1096. }
  1097. }
  1098. /**
  1099. * Builds a promise that is resolved when all the passed in promises are
  1100. * resolved.
  1101. * @param {array} array of data and/or promises to wait for.
  1102. * @return {Promise} New dependant promise.
  1103. */
  1104. Promise.all = function Promise_all(promises) {
  1105. var resolveAll, rejectAll;
  1106. var deferred = new Promise(function (resolve, reject) {
  1107. resolveAll = resolve;
  1108. rejectAll = reject;
  1109. });
  1110. var unresolved = promises.length;
  1111. var results = [];
  1112. if (unresolved === 0) {
  1113. resolveAll(results);
  1114. return deferred;
  1115. }
  1116. function reject(reason) {
  1117. if (deferred._status === STATUS_REJECTED) {
  1118. return;
  1119. }
  1120. results = [];
  1121. rejectAll(reason);
  1122. }
  1123. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1124. var promise = promises[i];
  1125. var resolve = (function(i) {
  1126. return function(value) {
  1127. if (deferred._status === STATUS_REJECTED) {
  1128. return;
  1129. }
  1130. results[i] = value;
  1131. unresolved--;
  1132. if (unresolved === 0) {
  1133. resolveAll(results);
  1134. }
  1135. };
  1136. })(i);
  1137. if (Promise.isPromise(promise)) {
  1138. promise.then(resolve, reject);
  1139. } else {
  1140. resolve(promise);
  1141. }
  1142. }
  1143. return deferred;
  1144. };
  1145. /**
  1146. * Checks if the value is likely a promise (has a 'then' function).
  1147. * @return {boolean} true if value is thenable
  1148. */
  1149. Promise.isPromise = function Promise_isPromise(value) {
  1150. return value && typeof value.then === 'function';
  1151. };
  1152. /**
  1153. * Creates resolved promise
  1154. * @param value resolve value
  1155. * @returns {Promise}
  1156. */
  1157. Promise.resolve = function Promise_resolve(value) {
  1158. return new Promise(function (resolve) { resolve(value); });
  1159. };
  1160. /**
  1161. * Creates rejected promise
  1162. * @param reason rejection value
  1163. * @returns {Promise}
  1164. */
  1165. Promise.reject = function Promise_reject(reason) {
  1166. return new Promise(function (resolve, reject) { reject(reason); });
  1167. };
  1168. Promise.prototype = {
  1169. _status: null,
  1170. _value: null,
  1171. _handlers: null,
  1172. _unhandledRejection: null,
  1173. _updateStatus: function Promise__updateStatus(status, value) {
  1174. if (this._status === STATUS_RESOLVED ||
  1175. this._status === STATUS_REJECTED) {
  1176. return;
  1177. }
  1178. if (status === STATUS_RESOLVED &&
  1179. Promise.isPromise(value)) {
  1180. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1181. this._updateStatus.bind(this, STATUS_REJECTED));
  1182. return;
  1183. }
  1184. this._status = status;
  1185. this._value = value;
  1186. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1187. this._unhandledRejection = true;
  1188. HandlerManager.addUnhandledRejection(this);
  1189. }
  1190. HandlerManager.scheduleHandlers(this);
  1191. },
  1192. _resolve: function Promise_resolve(value) {
  1193. this._updateStatus(STATUS_RESOLVED, value);
  1194. },
  1195. _reject: function Promise_reject(reason) {
  1196. this._updateStatus(STATUS_REJECTED, reason);
  1197. },
  1198. then: function Promise_then(onResolve, onReject) {
  1199. var nextPromise = new Promise(function (resolve, reject) {
  1200. this.resolve = resolve;
  1201. this.reject = reject;
  1202. });
  1203. this._handlers.push({
  1204. thisPromise: this,
  1205. onResolve: onResolve,
  1206. onReject: onReject,
  1207. nextPromise: nextPromise
  1208. });
  1209. HandlerManager.scheduleHandlers(this);
  1210. return nextPromise;
  1211. },
  1212. catch: function Promise_catch(onReject) {
  1213. return this.then(undefined, onReject);
  1214. }
  1215. };
  1216. globalScope.Promise = Promise;
  1217. })();
  1218. var StatTimer = (function StatTimerClosure() {
  1219. function rpad(str, pad, length) {
  1220. while (str.length < length) {
  1221. str += pad;
  1222. }
  1223. return str;
  1224. }
  1225. function StatTimer() {
  1226. this.started = {};
  1227. this.times = [];
  1228. this.enabled = true;
  1229. }
  1230. StatTimer.prototype = {
  1231. time: function StatTimer_time(name) {
  1232. if (!this.enabled) {
  1233. return;
  1234. }
  1235. if (name in this.started) {
  1236. warn('Timer is already running for ' + name);
  1237. }
  1238. this.started[name] = Date.now();
  1239. },
  1240. timeEnd: function StatTimer_timeEnd(name) {
  1241. if (!this.enabled) {
  1242. return;
  1243. }
  1244. if (!(name in this.started)) {
  1245. warn('Timer has not been started for ' + name);
  1246. }
  1247. this.times.push({
  1248. 'name': name,
  1249. 'start': this.started[name],
  1250. 'end': Date.now()
  1251. });
  1252. // Remove timer from started so it can be called again.
  1253. delete this.started[name];
  1254. },
  1255. toString: function StatTimer_toString() {
  1256. var i, ii;
  1257. var times = this.times;
  1258. var out = '';
  1259. // Find the longest name for padding purposes.
  1260. var longest = 0;
  1261. for (i = 0, ii = times.length; i < ii; ++i) {
  1262. var name = times[i]['name'];
  1263. if (name.length > longest) {
  1264. longest = name.length;
  1265. }
  1266. }
  1267. for (i = 0, ii = times.length; i < ii; ++i) {
  1268. var span = times[i];
  1269. var duration = span.end - span.start;
  1270. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1271. }
  1272. return out;
  1273. }
  1274. };
  1275. return StatTimer;
  1276. })();
  1277. PDFJS.createBlob = function createBlob(data, contentType) {
  1278. if (typeof Blob !== 'undefined') {
  1279. return new Blob([data], { type: contentType });
  1280. }
  1281. // Blob builder is deprecated in FF14 and removed in FF18.
  1282. var bb = new MozBlobBuilder();
  1283. bb.append(data);
  1284. return bb.getBlob(contentType);
  1285. };
  1286. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1287. // Blob/createObjectURL is not available, falling back to data schema.
  1288. var digits =
  1289. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1290. return function createObjectURL(data, contentType) {
  1291. if (!PDFJS.disableCreateObjectURL &&
  1292. typeof URL !== 'undefined' && URL.createObjectURL) {
  1293. var blob = PDFJS.createBlob(data, contentType);
  1294. return URL.createObjectURL(blob);
  1295. }
  1296. var buffer = 'data:' + contentType + ';base64,';
  1297. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1298. var b1 = data[i] & 0xFF;
  1299. var b2 = data[i + 1] & 0xFF;
  1300. var b3 = data[i + 2] & 0xFF;
  1301. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1302. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1303. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1304. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1305. }
  1306. return buffer;
  1307. };
  1308. })();
  1309. function MessageHandler(name, comObj) {
  1310. this.name = name;
  1311. this.comObj = comObj;
  1312. this.callbackIndex = 1;
  1313. this.postMessageTransfers = true;
  1314. var callbacksCapabilities = this.callbacksCapabilities = {};
  1315. var ah = this.actionHandler = {};
  1316. ah['console_log'] = [function ahConsoleLog(data) {
  1317. console.log.apply(console, data);
  1318. }];
  1319. ah['console_error'] = [function ahConsoleError(data) {
  1320. console.error.apply(console, data);
  1321. }];
  1322. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1323. UnsupportedManager.notify(data);
  1324. }];
  1325. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1326. var data = event.data;
  1327. if (data.isReply) {
  1328. var callbackId = data.callbackId;
  1329. if (data.callbackId in callbacksCapabilities) {
  1330. var callback = callbacksCapabilities[callbackId];
  1331. delete callbacksCapabilities[callbackId];
  1332. if ('error' in data) {
  1333. callback.reject(data.error);
  1334. } else {
  1335. callback.resolve(data.data);
  1336. }
  1337. } else {
  1338. error('Cannot resolve callback ' + callbackId);
  1339. }
  1340. } else if (data.action in ah) {
  1341. var action = ah[data.action];
  1342. if (data.callbackId) {
  1343. Promise.resolve().then(function () {
  1344. return action[0].call(action[1], data.data);
  1345. }).then(function (result) {
  1346. comObj.postMessage({
  1347. isReply: true,
  1348. callbackId: data.callbackId,
  1349. data: result
  1350. });
  1351. }, function (reason) {
  1352. comObj.postMessage({
  1353. isReply: true,
  1354. callbackId: data.callbackId,
  1355. error: reason
  1356. });
  1357. });
  1358. } else {
  1359. action[0].call(action[1], data.data);
  1360. }
  1361. } else {
  1362. error('Unknown action from worker: ' + data.action);
  1363. }
  1364. };
  1365. }
  1366. MessageHandler.prototype = {
  1367. on: function messageHandlerOn(actionName, handler, scope) {
  1368. var ah = this.actionHandler;
  1369. if (ah[actionName]) {
  1370. error('There is already an actionName called "' + actionName + '"');
  1371. }
  1372. ah[actionName] = [handler, scope];
  1373. },
  1374. /**
  1375. * Sends a message to the comObj to invoke the action with the supplied data.
  1376. * @param {String} actionName Action to call.
  1377. * @param {JSON} data JSON data to send.
  1378. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1379. */
  1380. send: function messageHandlerSend(actionName, data, transfers) {
  1381. var message = {
  1382. action: actionName,
  1383. data: data
  1384. };
  1385. this.postMessage(message, transfers);
  1386. },
  1387. /**
  1388. * Sends a message to the comObj to invoke the action with the supplied data.
  1389. * Expects that other side will callback with the response.
  1390. * @param {String} actionName Action to call.
  1391. * @param {JSON} data JSON data to send.
  1392. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1393. * @returns {Promise} Promise to be resolved with response data.
  1394. */
  1395. sendWithPromise:
  1396. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1397. var callbackId = this.callbackIndex++;
  1398. var message = {
  1399. action: actionName,
  1400. data: data,
  1401. callbackId: callbackId
  1402. };
  1403. var capability = createPromiseCapability();
  1404. this.callbacksCapabilities[callbackId] = capability;
  1405. try {
  1406. this.postMessage(message, transfers);
  1407. } catch (e) {
  1408. capability.reject(e);
  1409. }
  1410. return capability.promise;
  1411. },
  1412. /**
  1413. * Sends raw message to the comObj.
  1414. * @private
  1415. * @param message {Object} Raw message.
  1416. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1417. */
  1418. postMessage: function (message, transfers) {
  1419. if (transfers && this.postMessageTransfers) {
  1420. this.comObj.postMessage(message, transfers);
  1421. } else {
  1422. this.comObj.postMessage(message);
  1423. }
  1424. }
  1425. };
  1426. function loadJpegStream(id, imageUrl, objs) {
  1427. var img = new Image();
  1428. img.onload = (function loadJpegStream_onloadClosure() {
  1429. objs.resolve(id, img);
  1430. });
  1431. img.onerror = (function loadJpegStream_onerrorClosure() {
  1432. objs.resolve(id, null);
  1433. warn('Error during JPEG image loading');
  1434. });
  1435. img.src = imageUrl;
  1436. }
  1437. /**
  1438. * The maximum allowed image size in total pixels e.g. width * height. Images
  1439. * above this value will not be drawn. Use -1 for no limit.
  1440. * @var {number}
  1441. */
  1442. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1443. -1 : PDFJS.maxImageSize);
  1444. /**
  1445. * The url of where the predefined Adobe CMaps are located. Include trailing
  1446. * slash.
  1447. * @var {string}
  1448. */
  1449. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1450. /**
  1451. * Specifies if CMaps are binary packed.
  1452. * @var {boolean}
  1453. */
  1454. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1455. /*
  1456. * By default fonts are converted to OpenType fonts and loaded via font face
  1457. * rules. If disabled, the font will be rendered using a built in font renderer
  1458. * that constructs the glyphs with primitive path commands.
  1459. * @var {boolean}
  1460. */
  1461. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1462. false : PDFJS.disableFontFace);
  1463. /**
  1464. * Path for image resources, mainly for annotation icons. Include trailing
  1465. * slash.
  1466. * @var {string}
  1467. */
  1468. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1469. '' : PDFJS.imageResourcesPath);
  1470. /**
  1471. * Disable the web worker and run all code on the main thread. This will happen
  1472. * automatically if the browser doesn't support workers or sending typed arrays
  1473. * to workers.
  1474. * @var {boolean}
  1475. */
  1476. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1477. false : PDFJS.disableWorker);
  1478. /**
  1479. * Path and filename of the worker file. Required when the worker is enabled in
  1480. * development mode. If unspecified in the production build, the worker will be
  1481. * loaded based on the location of the pdf.js file.
  1482. * @var {string}
  1483. */
  1484. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1485. /**
  1486. * Disable range request loading of PDF files. When enabled and if the server
  1487. * supports partial content requests then the PDF will be fetched in chunks.
  1488. * Enabled (false) by default.
  1489. * @var {boolean}
  1490. */
  1491. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1492. false : PDFJS.disableRange);
  1493. /**
  1494. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1495. * will automatically keep fetching more data even if it isn't needed to display
  1496. * the current page. This default behavior can be disabled.
  1497. * @var {boolean}
  1498. */
  1499. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1500. false : PDFJS.disableAutoFetch);
  1501. /**
  1502. * Enables special hooks for debugging PDF.js.
  1503. * @var {boolean}
  1504. */
  1505. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1506. /**
  1507. * Enables transfer usage in postMessage for ArrayBuffers.
  1508. * @var {boolean}
  1509. */
  1510. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1511. true : PDFJS.postMessageTransfers);
  1512. /**
  1513. * Disables URL.createObjectURL usage.
  1514. * @var {boolean}
  1515. */
  1516. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1517. false : PDFJS.disableCreateObjectURL);
  1518. /**
  1519. * Disables WebGL usage.
  1520. * @var {boolean}
  1521. */
  1522. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1523. true : PDFJS.disableWebGL);
  1524. /**
  1525. * Enables CSS only zooming.
  1526. * @var {boolean}
  1527. */
  1528. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1529. false : PDFJS.useOnlyCssZoom);
  1530. /**
  1531. * Controls the logging level.
  1532. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1533. * - errors
  1534. * - warnings [default]
  1535. * - infos
  1536. * @var {number}
  1537. */
  1538. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1539. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1540. /**
  1541. * The maximum supported canvas size in total pixels e.g. width * height.
  1542. * The default value is 4096 * 4096. Use -1 for no limit.
  1543. * @var {number}
  1544. */
  1545. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1546. 16777216 : PDFJS.maxCanvasPixels);
  1547. /**
  1548. * Document initialization / loading parameters object.
  1549. *
  1550. * @typedef {Object} DocumentInitParameters
  1551. * @property {string} url - The URL of the PDF.
  1552. * @property {TypedArray} data - A typed array with PDF data.
  1553. * @property {Object} httpHeaders - Basic authentication headers.
  1554. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1555. * Access-Control requests should be made using credentials such as cookies
  1556. * or authorization headers. The default is false.
  1557. * @property {string} password - For decrypting password-protected PDFs.
  1558. * @property {TypedArray} initialData - A typed array with the first portion or
  1559. * all of the pdf data. Used by the extension since some data is already
  1560. * loaded before the switch to range requests.
  1561. */
  1562. /**
  1563. * @typedef {Object} PDFDocumentStats
  1564. * @property {Array} streamTypes - Used stream types in the document (an item
  1565. * is set to true if specific stream ID was used in the document).
  1566. * @property {Array} fontTypes - Used font type in the document (an item is set
  1567. * to true if specific font ID was used in the document).
  1568. */
  1569. /**
  1570. * This is the main entry point for loading a PDF and interacting with it.
  1571. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1572. * is used, which means it must follow the same origin rules that any XHR does
  1573. * e.g. No cross domain requests without CORS.
  1574. *
  1575. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  1576. * where a PDF is located, a typed array (Uint8Array) already populated with
  1577. * data or parameter object.
  1578. *
  1579. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  1580. * to manually serve range requests for data in the PDF. See viewer.js for
  1581. * an example of pdfDataRangeTransport's interface.
  1582. *
  1583. * @param {function} passwordCallback is optional. It is used to request a
  1584. * password if wrong or no password was provided. The callback receives two
  1585. * parameters: function that needs to be called with new password and reason
  1586. * (see {PasswordResponses}).
  1587. *
  1588. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  1589. * object.
  1590. */
  1591. PDFJS.getDocument = function getDocument(source,
  1592. pdfDataRangeTransport,
  1593. passwordCallback,
  1594. progressCallback) {
  1595. var workerInitializedCapability, workerReadyCapability, transport;
  1596. if (typeof source === 'string') {
  1597. source = { url: source };
  1598. } else if (isArrayBuffer(source)) {
  1599. source = { data: source };
  1600. } else if (typeof source !== 'object') {
  1601. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1602. 'string or a parameter object');
  1603. }
  1604. if (!source.url && !source.data) {
  1605. error('Invalid parameter array, need either .data or .url');
  1606. }
  1607. // copy/use all keys as is except 'url' -- full path is required
  1608. var params = {};
  1609. for (var key in source) {
  1610. if (key === 'url' && typeof window !== 'undefined') {
  1611. params[key] = combineUrl(window.location.href, source[key]);
  1612. continue;
  1613. }
  1614. params[key] = source[key];
  1615. }
  1616. workerInitializedCapability = createPromiseCapability();
  1617. workerReadyCapability = createPromiseCapability();
  1618. transport = new WorkerTransport(workerInitializedCapability,
  1619. workerReadyCapability, pdfDataRangeTransport,
  1620. progressCallback);
  1621. workerInitializedCapability.promise.then(function transportInitialized() {
  1622. transport.passwordCallback = passwordCallback;
  1623. transport.fetchDocument(params);
  1624. });
  1625. return workerReadyCapability.promise;
  1626. };
  1627. /**
  1628. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1629. * properties that can be read synchronously.
  1630. * @class
  1631. */
  1632. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1633. function PDFDocumentProxy(pdfInfo, transport) {
  1634. this.pdfInfo = pdfInfo;
  1635. this.transport = transport;
  1636. }
  1637. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1638. /**
  1639. * @return {number} Total number of pages the PDF contains.
  1640. */
  1641. get numPages() {
  1642. return this.pdfInfo.numPages;
  1643. },
  1644. /**
  1645. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1646. * unique.
  1647. */
  1648. get fingerprint() {
  1649. return this.pdfInfo.fingerprint;
  1650. },
  1651. /**
  1652. * @param {number} pageNumber The page number to get. The first page is 1.
  1653. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1654. * object.
  1655. */
  1656. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1657. return this.transport.getPage(pageNumber);
  1658. },
  1659. /**
  1660. * @param {{num: number, gen: number}} ref The page reference. Must have
  1661. * the 'num' and 'gen' properties.
  1662. * @return {Promise} A promise that is resolved with the page index that is
  1663. * associated with the reference.
  1664. */
  1665. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1666. return this.transport.getPageIndex(ref);
  1667. },
  1668. /**
  1669. * @return {Promise} A promise that is resolved with a lookup table for
  1670. * mapping named destinations to reference numbers.
  1671. */
  1672. getDestinations: function PDFDocumentProxy_getDestinations() {
  1673. return this.transport.getDestinations();
  1674. },
  1675. /**
  1676. * @return {Promise} A promise that is resolved with a lookup table for
  1677. * mapping named attachments to their content.
  1678. */
  1679. getAttachments: function PDFDocumentProxy_getAttachments() {
  1680. return this.transport.getAttachments();
  1681. },
  1682. /**
  1683. * @return {Promise} A promise that is resolved with an array of all the
  1684. * JavaScript strings in the name tree.
  1685. */
  1686. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1687. return this.transport.getJavaScript();
  1688. },
  1689. /**
  1690. * @return {Promise} A promise that is resolved with an {Array} that is a
  1691. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1692. * [
  1693. * {
  1694. * title: string,
  1695. * bold: boolean,
  1696. * italic: boolean,
  1697. * color: rgb array,
  1698. * dest: dest obj,
  1699. * items: array of more items like this
  1700. * },
  1701. * ...
  1702. * ].
  1703. */
  1704. getOutline: function PDFDocumentProxy_getOutline() {
  1705. return this.transport.getOutline();
  1706. },
  1707. /**
  1708. * @return {Promise} A promise that is resolved with an {Object} that has
  1709. * info and metadata properties. Info is an {Object} filled with anything
  1710. * available in the information dictionary and similarly metadata is a
  1711. * {Metadata} object with information from the metadata section of the PDF.
  1712. */
  1713. getMetadata: function PDFDocumentProxy_getMetadata() {
  1714. return this.transport.getMetadata();
  1715. },
  1716. /**
  1717. * @return {Promise} A promise that is resolved with a TypedArray that has
  1718. * the raw data from the PDF.
  1719. */
  1720. getData: function PDFDocumentProxy_getData() {
  1721. return this.transport.getData();
  1722. },
  1723. /**
  1724. * @return {Promise} A promise that is resolved when the document's data
  1725. * is loaded. It is resolved with an {Object} that contains the length
  1726. * property that indicates size of the PDF data in bytes.
  1727. */
  1728. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1729. return this.transport.downloadInfoCapability.promise;
  1730. },
  1731. /**
  1732. * @returns {Promise} A promise this is resolved with current stats about
  1733. * document structures (see {@link PDFDocumentStats}).
  1734. */
  1735. getStats: function PDFDocumentProxy_getStats() {
  1736. return this.transport.getStats();
  1737. },
  1738. /**
  1739. * Cleans up resources allocated by the document, e.g. created @font-face.
  1740. */
  1741. cleanup: function PDFDocumentProxy_cleanup() {
  1742. this.transport.startCleanup();
  1743. },
  1744. /**
  1745. * Destroys current document instance and terminates worker.
  1746. */
  1747. destroy: function PDFDocumentProxy_destroy() {
  1748. this.transport.destroy();
  1749. }
  1750. };
  1751. return PDFDocumentProxy;
  1752. })();
  1753. /**
  1754. * Page text content.
  1755. *
  1756. * @typedef {Object} TextContent
  1757. * @property {array} items - array of {@link TextItem}
  1758. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1759. * name.
  1760. */
  1761. /**
  1762. * Page text content part.
  1763. *
  1764. * @typedef {Object} TextItem
  1765. * @property {string} str - text content.
  1766. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1767. * @property {array} transform - transformation matrix.
  1768. * @property {number} width - width in device space.
  1769. * @property {number} height - height in device space.
  1770. * @property {string} fontName - font name used by pdf.js for converted font.
  1771. */
  1772. /**
  1773. * Text style.
  1774. *
  1775. * @typedef {Object} TextStyle
  1776. * @property {number} ascent - font ascent.
  1777. * @property {number} descent - font descent.
  1778. * @property {boolean} vertical - text is in vertical mode.
  1779. * @property {string} fontFamily - possible font family
  1780. */
  1781. /**
  1782. * Page render parameters.
  1783. *
  1784. * @typedef {Object} RenderParameters
  1785. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1786. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1787. * calling of PDFPage.getViewport method.
  1788. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1789. * (default value is 'display').
  1790. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1791. * endLayout and appendImage functions.
  1792. * @property {function} continueCallback - (optional) A function that will be
  1793. * called each time the rendering is paused. To continue
  1794. * rendering call the function that is the first argument
  1795. * to the callback.
  1796. */
  1797. /**
  1798. * PDF page operator list.
  1799. *
  1800. * @typedef {Object} PDFOperatorList
  1801. * @property {Array} fnArray - Array containing the operator functions.
  1802. * @property {Array} argsArray - Array containing the arguments of the
  1803. * functions.
  1804. */
  1805. /**
  1806. * Proxy to a PDFPage in the worker thread.
  1807. * @class
  1808. */
  1809. var PDFPageProxy = (function PDFPageProxyClosure() {
  1810. function PDFPageProxy(pageIndex, pageInfo, transport) {
  1811. this.pageIndex = pageIndex;
  1812. this.pageInfo = pageInfo;
  1813. this.transport = transport;
  1814. this.stats = new StatTimer();
  1815. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  1816. this.commonObjs = transport.commonObjs;
  1817. this.objs = new PDFObjects();
  1818. this.cleanupAfterRender = false;
  1819. this.pendingDestroy = false;
  1820. this.intentStates = {};
  1821. }
  1822. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  1823. /**
  1824. * @return {number} Page number of the page. First page is 1.
  1825. */
  1826. get pageNumber() {
  1827. return this.pageIndex + 1;
  1828. },
  1829. /**
  1830. * @return {number} The number of degrees the page is rotated clockwise.
  1831. */
  1832. get rotate() {
  1833. return this.pageInfo.rotate;
  1834. },
  1835. /**
  1836. * @return {Object} The reference that points to this page. It has 'num' and
  1837. * 'gen' properties.
  1838. */
  1839. get ref() {
  1840. return this.pageInfo.ref;
  1841. },
  1842. /**
  1843. * @return {Array} An array of the visible portion of the PDF page in the
  1844. * user space units - [x1, y1, x2, y2].
  1845. */
  1846. get view() {
  1847. return this.pageInfo.view;
  1848. },
  1849. /**
  1850. * @param {number} scale The desired scale of the viewport.
  1851. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  1852. * defaults to the page rotation.
  1853. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  1854. * along with transforms required for rendering.
  1855. */
  1856. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  1857. if (arguments.length < 2) {
  1858. rotate = this.rotate;
  1859. }
  1860. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  1861. },
  1862. /**
  1863. * @return {Promise} A promise that is resolved with an {Array} of the
  1864. * annotation objects.
  1865. */
  1866. getAnnotations: function PDFPageProxy_getAnnotations() {
  1867. if (this.annotationsPromise) {
  1868. return this.annotationsPromise;
  1869. }
  1870. var promise = this.transport.getAnnotations(this.pageIndex);
  1871. this.annotationsPromise = promise;
  1872. return promise;
  1873. },
  1874. /**
  1875. * Begins the process of rendering a page to the desired context.
  1876. * @param {RenderParameters} params Page render parameters.
  1877. * @return {RenderTask} An object that contains the promise, which
  1878. * is resolved when the page finishes rendering.
  1879. */
  1880. render: function PDFPageProxy_render(params) {
  1881. var stats = this.stats;
  1882. stats.time('Overall');
  1883. // If there was a pending destroy cancel it so no cleanup happens during
  1884. // this call to render.
  1885. this.pendingDestroy = false;
  1886. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  1887. if (!this.intentStates[renderingIntent]) {
  1888. this.intentStates[renderingIntent] = {};
  1889. }
  1890. var intentState = this.intentStates[renderingIntent];
  1891. // If there's no displayReadyCapability yet, then the operatorList
  1892. // was never requested before. Make the request and create the promise.
  1893. if (!intentState.displayReadyCapability) {
  1894. intentState.receivingOperatorList = true;
  1895. intentState.displayReadyCapability = createPromiseCapability();
  1896. intentState.operatorList = {
  1897. fnArray: [],
  1898. argsArray: [],
  1899. lastChunk: false
  1900. };
  1901. this.stats.time('Page Request');
  1902. this.transport.messageHandler.send('RenderPageRequest', {
  1903. pageIndex: this.pageNumber - 1,
  1904. intent: renderingIntent
  1905. });
  1906. }
  1907. var internalRenderTask = new InternalRenderTask(complete, params,
  1908. this.objs,
  1909. this.commonObjs,
  1910. intentState.operatorList,
  1911. this.pageNumber);
  1912. if (!intentState.renderTasks) {
  1913. intentState.renderTasks = [];
  1914. }
  1915. intentState.renderTasks.push(internalRenderTask);
  1916. var renderTask = new RenderTask(internalRenderTask);
  1917. var self = this;
  1918. intentState.displayReadyCapability.promise.then(
  1919. function pageDisplayReadyPromise(transparency) {
  1920. if (self.pendingDestroy) {
  1921. complete();
  1922. return;
  1923. }
  1924. stats.time('Rendering');
  1925. internalRenderTask.initalizeGraphics(transparency);
  1926. internalRenderTask.operatorListChanged();
  1927. },
  1928. function pageDisplayReadPromiseError(reason) {
  1929. complete(reason);
  1930. }
  1931. );
  1932. function complete(error) {
  1933. var i = intentState.renderTasks.indexOf(internalRenderTask);
  1934. if (i >= 0) {
  1935. intentState.renderTasks.splice(i, 1);
  1936. }
  1937. if (self.cleanupAfterRender) {
  1938. self.pendingDestroy = true;
  1939. }
  1940. self._tryDestroy();
  1941. if (error) {
  1942. internalRenderTask.capability.reject(error);
  1943. } else {
  1944. internalRenderTask.capability.resolve();
  1945. }
  1946. stats.timeEnd('Rendering');
  1947. stats.timeEnd('Overall');
  1948. }
  1949. return renderTask;
  1950. },
  1951. /**
  1952. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  1953. * object that represents page's operator list.
  1954. */
  1955. getOperatorList: function PDFPageProxy_getOperatorList() {
  1956. function operatorListChanged() {
  1957. if (intentState.operatorList.lastChunk) {
  1958. intentState.opListReadCapability.resolve(intentState.operatorList);
  1959. }
  1960. }
  1961. var renderingIntent = 'oplist';
  1962. if (!this.intentStates[renderingIntent]) {
  1963. this.intentStates[renderingIntent] = {};
  1964. }
  1965. var intentState = this.intentStates[renderingIntent];
  1966. if (!intentState.opListReadCapability) {
  1967. var opListTask = {};
  1968. opListTask.operatorListChanged = operatorListChanged;
  1969. intentState.receivingOperatorList = true;
  1970. intentState.opListReadCapability = createPromiseCapability();
  1971. intentState.renderTasks = [];
  1972. intentState.renderTasks.push(opListTask);
  1973. intentState.operatorList = {
  1974. fnArray: [],
  1975. argsArray: [],
  1976. lastChunk: false
  1977. };
  1978. this.transport.messageHandler.send('RenderPageRequest', {
  1979. pageIndex: this.pageIndex,
  1980. intent: renderingIntent
  1981. });
  1982. }
  1983. return intentState.opListReadCapability.promise;
  1984. },
  1985. /**
  1986. * @return {Promise} That is resolved a {@link TextContent}
  1987. * object that represent the page text content.
  1988. */
  1989. getTextContent: function PDFPageProxy_getTextContent() {
  1990. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  1991. pageIndex: this.pageNumber - 1
  1992. });
  1993. },
  1994. /**
  1995. * Destroys resources allocated by the page.
  1996. */
  1997. destroy: function PDFPageProxy_destroy() {
  1998. this.pendingDestroy = true;
  1999. this._tryDestroy();
  2000. },
  2001. /**
  2002. * For internal use only. Attempts to clean up if rendering is in a state
  2003. * where that's possible.
  2004. * @ignore
  2005. */
  2006. _tryDestroy: function PDFPageProxy__destroy() {
  2007. if (!this.pendingDestroy ||
  2008. Object.keys(this.intentStates).some(function(intent) {
  2009. var intentState = this.intentStates[intent];
  2010. return (intentState.renderTasks.length !== 0 ||
  2011. intentState.receivingOperatorList);
  2012. }, this)) {
  2013. return;
  2014. }
  2015. Object.keys(this.intentStates).forEach(function(intent) {
  2016. delete this.intentStates[intent];
  2017. }, this);
  2018. this.objs.clear();
  2019. this.annotationsPromise = null;
  2020. this.pendingDestroy = false;
  2021. },
  2022. /**
  2023. * For internal use only.
  2024. * @ignore
  2025. */
  2026. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2027. intent) {
  2028. var intentState = this.intentStates[intent];
  2029. // TODO Refactor RenderPageRequest to separate rendering
  2030. // and operator list logic
  2031. if (intentState.displayReadyCapability) {
  2032. intentState.displayReadyCapability.resolve(transparency);
  2033. }
  2034. },
  2035. /**
  2036. * For internal use only.
  2037. * @ignore
  2038. */
  2039. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2040. intent) {
  2041. var intentState = this.intentStates[intent];
  2042. var i, ii;
  2043. // Add the new chunk to the current operator list.
  2044. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2045. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2046. intentState.operatorList.argsArray.push(
  2047. operatorListChunk.argsArray[i]);
  2048. }
  2049. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2050. // Notify all the rendering tasks there are more operators to be consumed.
  2051. for (i = 0; i < intentState.renderTasks.length; i++) {
  2052. intentState.renderTasks[i].operatorListChanged();
  2053. }
  2054. if (operatorListChunk.lastChunk) {
  2055. intentState.receivingOperatorList = false;
  2056. this._tryDestroy();
  2057. }
  2058. }
  2059. };
  2060. return PDFPageProxy;
  2061. })();
  2062. /**
  2063. * For internal use only.
  2064. * @ignore
  2065. */
  2066. var WorkerTransport = (function WorkerTransportClosure() {
  2067. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  2068. pdfDataRangeTransport, progressCallback) {
  2069. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2070. this.workerInitializedCapability = workerInitializedCapability;
  2071. this.workerReadyCapability = workerReadyCapability;
  2072. this.progressCallback = progressCallback;
  2073. this.commonObjs = new PDFObjects();
  2074. this.pageCache = [];
  2075. this.pagePromises = [];
  2076. this.downloadInfoCapability = createPromiseCapability();
  2077. this.passwordCallback = null;
  2078. // If worker support isn't disabled explicit and the browser has worker
  2079. // support, create a new web worker and test if it/the browser fullfills
  2080. // all requirements to run parts of pdf.js in a web worker.
  2081. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2082. // as it arrives on the worker. Chrome added this with version 15.
  2083. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  2084. var workerSrc = PDFJS.workerSrc;
  2085. if (!workerSrc) {
  2086. error('No PDFJS.workerSrc specified');
  2087. }
  2088. try {
  2089. // Some versions of FF can't create a worker on localhost, see:
  2090. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  2091. var worker = new Worker(workerSrc);
  2092. var messageHandler = new MessageHandler('main', worker);
  2093. this.messageHandler = messageHandler;
  2094. messageHandler.on('test', function transportTest(data) {
  2095. var supportTypedArray = data && data.supportTypedArray;
  2096. if (supportTypedArray) {
  2097. this.worker = worker;
  2098. if (!data.supportTransfers) {
  2099. PDFJS.postMessageTransfers = false;
  2100. }
  2101. this.setupMessageHandler(messageHandler);
  2102. workerInitializedCapability.resolve();
  2103. } else {
  2104. this.setupFakeWorker();
  2105. }
  2106. }.bind(this));
  2107. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  2108. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  2109. // typed array. Also, checking if we can use transfers.
  2110. try {
  2111. messageHandler.send('test', testObj, [testObj.buffer]);
  2112. } catch (ex) {
  2113. info('Cannot use postMessage transfers');
  2114. testObj[0] = 0;
  2115. messageHandler.send('test', testObj);
  2116. }
  2117. return;
  2118. } catch (e) {
  2119. info('The worker has been disabled.');
  2120. }
  2121. }
  2122. // Either workers are disabled, not supported or have thrown an exception.
  2123. // Thus, we fallback to a faked worker.
  2124. this.setupFakeWorker();
  2125. }
  2126. WorkerTransport.prototype = {
  2127. destroy: function WorkerTransport_destroy() {
  2128. this.pageCache = [];
  2129. this.pagePromises = [];
  2130. var self = this;
  2131. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2132. FontLoader.clear();
  2133. if (self.worker) {
  2134. self.worker.terminate();
  2135. }
  2136. });
  2137. },
  2138. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2139. globalScope.PDFJS.disableWorker = true;
  2140. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2141. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2142. // In the developer build load worker_loader which in turn loads all the
  2143. // other files and resolves the promise. In production only the
  2144. // pdf.worker.js file is needed.
  2145. Util.loadScript(PDFJS.workerSrc, function() {
  2146. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2147. });
  2148. }
  2149. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2150. warn('Setting up fake worker.');
  2151. // If we don't use a worker, just post/sendMessage to the main thread.
  2152. var fakeWorker = {
  2153. postMessage: function WorkerTransport_postMessage(obj) {
  2154. fakeWorker.onmessage({data: obj});
  2155. },
  2156. terminate: function WorkerTransport_terminate() {}
  2157. };
  2158. var messageHandler = new MessageHandler('main', fakeWorker);
  2159. this.setupMessageHandler(messageHandler);
  2160. // If the main thread is our worker, setup the handling for the messages
  2161. // the main thread sends to it self.
  2162. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2163. this.workerInitializedCapability.resolve();
  2164. }.bind(this));
  2165. },
  2166. setupMessageHandler:
  2167. function WorkerTransport_setupMessageHandler(messageHandler) {
  2168. this.messageHandler = messageHandler;
  2169. function updatePassword(password) {
  2170. messageHandler.send('UpdatePassword', password);
  2171. }
  2172. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2173. if (pdfDataRangeTransport) {
  2174. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2175. messageHandler.send('OnDataRange', {
  2176. begin: begin,
  2177. chunk: chunk
  2178. });
  2179. });
  2180. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2181. messageHandler.send('OnDataProgress', {
  2182. loaded: loaded
  2183. });
  2184. });
  2185. messageHandler.on('RequestDataRange',
  2186. function transportDataRange(data) {
  2187. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2188. }, this);
  2189. }
  2190. messageHandler.on('GetDoc', function transportDoc(data) {
  2191. var pdfInfo = data.pdfInfo;
  2192. this.numPages = data.pdfInfo.numPages;
  2193. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2194. this.pdfDocument = pdfDocument;
  2195. this.workerReadyCapability.resolve(pdfDocument);
  2196. }, this);
  2197. messageHandler.on('NeedPassword', function transportPassword(data) {
  2198. if (this.passwordCallback) {
  2199. return this.passwordCallback(updatePassword,
  2200. PasswordResponses.NEED_PASSWORD);
  2201. }
  2202. this.workerReadyCapability.reject(data.exception.message,
  2203. data.exception);
  2204. }, this);
  2205. messageHandler.on('IncorrectPassword', function transportBadPass(data) {
  2206. if (this.passwordCallback) {
  2207. return this.passwordCallback(updatePassword,
  2208. PasswordResponses.INCORRECT_PASSWORD);
  2209. }
  2210. this.workerReadyCapability.reject(data.exception.message,
  2211. data.exception);
  2212. }, this);
  2213. messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
  2214. this.workerReadyCapability.reject(data.exception.name, data.exception);
  2215. }, this);
  2216. messageHandler.on('MissingPDF', function transportMissingPDF(data) {
  2217. this.workerReadyCapability.reject(data.exception.message,
  2218. data.exception);
  2219. }, this);
  2220. messageHandler.on('UnknownError', function transportUnknownError(data) {
  2221. this.workerReadyCapability.reject(data.exception.message,
  2222. data.exception);
  2223. }, this);
  2224. messageHandler.on('DataLoaded', function transportPage(data) {
  2225. this.downloadInfoCapability.resolve(data);
  2226. }, this);
  2227. messageHandler.on('StartRenderPage', function transportRender(data) {
  2228. var page = this.pageCache[data.pageIndex];
  2229. page.stats.timeEnd('Page Request');
  2230. page._startRenderPage(data.transparency, data.intent);
  2231. }, this);
  2232. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2233. var page = this.pageCache[data.pageIndex];
  2234. page._renderPageChunk(data.operatorList, data.intent);
  2235. }, this);
  2236. messageHandler.on('commonobj', function transportObj(data) {
  2237. var id = data[0];
  2238. var type = data[1];
  2239. if (this.commonObjs.hasData(id)) {
  2240. return;
  2241. }
  2242. switch (type) {
  2243. case 'Font':
  2244. var exportedData = data[2];
  2245. var font;
  2246. if ('error' in exportedData) {
  2247. var error = exportedData.error;
  2248. warn('Error during font loading: ' + error);
  2249. this.commonObjs.resolve(id, error);
  2250. break;
  2251. } else {
  2252. font = new FontFace(exportedData);
  2253. }
  2254. FontLoader.bind(
  2255. [font],
  2256. function fontReady(fontObjs) {
  2257. this.commonObjs.resolve(id, font);
  2258. }.bind(this)
  2259. );
  2260. break;
  2261. case 'FontPath':
  2262. this.commonObjs.resolve(id, data[2]);
  2263. break;
  2264. default:
  2265. error('Got unknown common object type ' + type);
  2266. }
  2267. }, this);
  2268. messageHandler.on('obj', function transportObj(data) {
  2269. var id = data[0];
  2270. var pageIndex = data[1];
  2271. var type = data[2];
  2272. var pageProxy = this.pageCache[pageIndex];
  2273. var imageData;
  2274. if (pageProxy.objs.hasData(id)) {
  2275. return;
  2276. }
  2277. switch (type) {
  2278. case 'JpegStream':
  2279. imageData = data[3];
  2280. loadJpegStream(id, imageData, pageProxy.objs);
  2281. break;
  2282. case 'Image':
  2283. imageData = data[3];
  2284. pageProxy.objs.resolve(id, imageData);
  2285. // heuristics that will allow not to store large data
  2286. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2287. if (imageData && 'data' in imageData &&
  2288. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2289. pageProxy.cleanupAfterRender = true;
  2290. }
  2291. break;
  2292. default:
  2293. error('Got unknown object type ' + type);
  2294. }
  2295. }, this);
  2296. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2297. if (this.progressCallback) {
  2298. this.progressCallback({
  2299. loaded: data.loaded,
  2300. total: data.total
  2301. });
  2302. }
  2303. }, this);
  2304. messageHandler.on('DocError', function transportDocError(data) {
  2305. this.workerReadyCapability.reject(data);
  2306. }, this);
  2307. messageHandler.on('PageError', function transportError(data) {
  2308. var page = this.pageCache[data.pageNum - 1];
  2309. var intentState = page.intentStates[data.intent];
  2310. if (intentState.displayReadyCapability.promise) {
  2311. intentState.displayReadyCapability.reject(data.error);
  2312. } else {
  2313. error(data.error);
  2314. }
  2315. }, this);
  2316. messageHandler.on('JpegDecode', function(data) {
  2317. var imageUrl = data[0];
  2318. var components = data[1];
  2319. if (components !== 3 && components !== 1) {
  2320. return Promise.reject(
  2321. new Error('Only 3 components or 1 component can be returned'));
  2322. }
  2323. return new Promise(function (resolve, reject) {
  2324. var img = new Image();
  2325. img.onload = function () {
  2326. var width = img.width;
  2327. var height = img.height;
  2328. var size = width * height;
  2329. var rgbaLength = size * 4;
  2330. var buf = new Uint8Array(size * components);
  2331. var tmpCanvas = createScratchCanvas(width, height);
  2332. var tmpCtx = tmpCanvas.getContext('2d');
  2333. tmpCtx.drawImage(img, 0, 0);
  2334. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2335. var i, j;
  2336. if (components === 3) {
  2337. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2338. buf[j] = data[i];
  2339. buf[j + 1] = data[i + 1];
  2340. buf[j + 2] = data[i + 2];
  2341. }
  2342. } else if (components === 1) {
  2343. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2344. buf[j] = data[i];
  2345. }
  2346. }
  2347. resolve({ data: buf, width: width, height: height});
  2348. };
  2349. img.onerror = function () {
  2350. reject(new Error('JpegDecode failed to load image'));
  2351. };
  2352. img.src = imageUrl;
  2353. });
  2354. });
  2355. },
  2356. fetchDocument: function WorkerTransport_fetchDocument(source) {
  2357. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2358. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2359. this.messageHandler.send('GetDocRequest', {
  2360. source: source,
  2361. disableRange: PDFJS.disableRange,
  2362. maxImageSize: PDFJS.maxImageSize,
  2363. cMapUrl: PDFJS.cMapUrl,
  2364. cMapPacked: PDFJS.cMapPacked,
  2365. disableFontFace: PDFJS.disableFontFace,
  2366. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2367. verbosity: PDFJS.verbosity
  2368. });
  2369. },
  2370. getData: function WorkerTransport_getData() {
  2371. return this.messageHandler.sendWithPromise('GetData', null);
  2372. },
  2373. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2374. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2375. (pageNumber|0) !== pageNumber) {
  2376. return Promise.reject(new Error('Invalid page request'));
  2377. }
  2378. var pageIndex = pageNumber - 1;
  2379. if (pageIndex in this.pagePromises) {
  2380. return this.pagePromises[pageIndex];
  2381. }
  2382. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2383. pageIndex: pageIndex
  2384. }).then(function (pageInfo) {
  2385. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2386. this.pageCache[pageIndex] = page;
  2387. return page;
  2388. }.bind(this));
  2389. this.pagePromises[pageIndex] = promise;
  2390. return promise;
  2391. },
  2392. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2393. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2394. },
  2395. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2396. return this.messageHandler.sendWithPromise('GetAnnotations',
  2397. { pageIndex: pageIndex });
  2398. },
  2399. getDestinations: function WorkerTransport_getDestinations() {
  2400. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2401. },
  2402. getAttachments: function WorkerTransport_getAttachments() {
  2403. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2404. },
  2405. getJavaScript: function WorkerTransport_getJavaScript() {
  2406. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2407. },
  2408. getOutline: function WorkerTransport_getOutline() {
  2409. return this.messageHandler.sendWithPromise('GetOutline', null);
  2410. },
  2411. getMetadata: function WorkerTransport_getMetadata() {
  2412. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2413. then(function transportMetadata(results) {
  2414. return {
  2415. info: results[0],
  2416. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2417. };
  2418. });
  2419. },
  2420. getStats: function WorkerTransport_getStats() {
  2421. return this.messageHandler.sendWithPromise('GetStats', null);
  2422. },
  2423. startCleanup: function WorkerTransport_startCleanup() {
  2424. this.messageHandler.sendWithPromise('Cleanup', null).
  2425. then(function endCleanup() {
  2426. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2427. var page = this.pageCache[i];
  2428. if (page) {
  2429. page.destroy();
  2430. }
  2431. }
  2432. this.commonObjs.clear();
  2433. FontLoader.clear();
  2434. }.bind(this));
  2435. }
  2436. };
  2437. return WorkerTransport;
  2438. })();
  2439. /**
  2440. * A PDF document and page is built of many objects. E.g. there are objects
  2441. * for fonts, images, rendering code and such. These objects might get processed
  2442. * inside of a worker. The `PDFObjects` implements some basic functions to
  2443. * manage these objects.
  2444. * @ignore
  2445. */
  2446. var PDFObjects = (function PDFObjectsClosure() {
  2447. function PDFObjects() {
  2448. this.objs = {};
  2449. }
  2450. PDFObjects.prototype = {
  2451. /**
  2452. * Internal function.
  2453. * Ensures there is an object defined for `objId`.
  2454. */
  2455. ensureObj: function PDFObjects_ensureObj(objId) {
  2456. if (this.objs[objId]) {
  2457. return this.objs[objId];
  2458. }
  2459. var obj = {
  2460. capability: createPromiseCapability(),
  2461. data: null,
  2462. resolved: false
  2463. };
  2464. this.objs[objId] = obj;
  2465. return obj;
  2466. },
  2467. /**
  2468. * If called *without* callback, this returns the data of `objId` but the
  2469. * object needs to be resolved. If it isn't, this function throws.
  2470. *
  2471. * If called *with* a callback, the callback is called with the data of the
  2472. * object once the object is resolved. That means, if you call this
  2473. * function and the object is already resolved, the callback gets called
  2474. * right away.
  2475. */
  2476. get: function PDFObjects_get(objId, callback) {
  2477. // If there is a callback, then the get can be async and the object is
  2478. // not required to be resolved right now
  2479. if (callback) {
  2480. this.ensureObj(objId).capability.promise.then(callback);
  2481. return null;
  2482. }
  2483. // If there isn't a callback, the user expects to get the resolved data
  2484. // directly.
  2485. var obj = this.objs[objId];
  2486. // If there isn't an object yet or the object isn't resolved, then the
  2487. // data isn't ready yet!
  2488. if (!obj || !obj.resolved) {
  2489. error('Requesting object that isn\'t resolved yet ' + objId);
  2490. }
  2491. return obj.data;
  2492. },
  2493. /**
  2494. * Resolves the object `objId` with optional `data`.
  2495. */
  2496. resolve: function PDFObjects_resolve(objId, data) {
  2497. var obj = this.ensureObj(objId);
  2498. obj.resolved = true;
  2499. obj.data = data;
  2500. obj.capability.resolve(data);
  2501. },
  2502. isResolved: function PDFObjects_isResolved(objId) {
  2503. var objs = this.objs;
  2504. if (!objs[objId]) {
  2505. return false;
  2506. } else {
  2507. return objs[objId].resolved;
  2508. }
  2509. },
  2510. hasData: function PDFObjects_hasData(objId) {
  2511. return this.isResolved(objId);
  2512. },
  2513. /**
  2514. * Returns the data of `objId` if object exists, null otherwise.
  2515. */
  2516. getData: function PDFObjects_getData(objId) {
  2517. var objs = this.objs;
  2518. if (!objs[objId] || !objs[objId].resolved) {
  2519. return null;
  2520. } else {
  2521. return objs[objId].data;
  2522. }
  2523. },
  2524. clear: function PDFObjects_clear() {
  2525. this.objs = {};
  2526. }
  2527. };
  2528. return PDFObjects;
  2529. })();
  2530. /**
  2531. * Allows controlling of the rendering tasks.
  2532. * @class
  2533. */
  2534. var RenderTask = (function RenderTaskClosure() {
  2535. function RenderTask(internalRenderTask) {
  2536. this.internalRenderTask = internalRenderTask;
  2537. /**
  2538. * Promise for rendering task completion.
  2539. * @type {Promise}
  2540. */
  2541. this.promise = this.internalRenderTask.capability.promise;
  2542. }
  2543. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2544. /**
  2545. * Cancels the rendering task. If the task is currently rendering it will
  2546. * not be cancelled until graphics pauses with a timeout. The promise that
  2547. * this object extends will resolved when cancelled.
  2548. */
  2549. cancel: function RenderTask_cancel() {
  2550. this.internalRenderTask.cancel();
  2551. },
  2552. /**
  2553. * Registers callback to indicate the rendering task completion.
  2554. *
  2555. * @param {function} onFulfilled The callback for the rendering completion.
  2556. * @param {function} onRejected The callback for the rendering failure.
  2557. * @return {Promise} A promise that is resolved after the onFulfilled or
  2558. * onRejected callback.
  2559. */
  2560. then: function RenderTask_then(onFulfilled, onRejected) {
  2561. return this.promise.then(onFulfilled, onRejected);
  2562. }
  2563. };
  2564. return RenderTask;
  2565. })();
  2566. /**
  2567. * For internal use only.
  2568. * @ignore
  2569. */
  2570. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2571. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2572. pageNumber) {
  2573. this.callback = callback;
  2574. this.params = params;
  2575. this.objs = objs;
  2576. this.commonObjs = commonObjs;
  2577. this.operatorListIdx = null;
  2578. this.operatorList = operatorList;
  2579. this.pageNumber = pageNumber;
  2580. this.running = false;
  2581. this.graphicsReadyCallback = null;
  2582. this.graphicsReady = false;
  2583. this.cancelled = false;
  2584. this.capability = createPromiseCapability();
  2585. // caching this-bound methods
  2586. this._continueBound = this._continue.bind(this);
  2587. this._scheduleNextBound = this._scheduleNext.bind(this);
  2588. this._nextBound = this._next.bind(this);
  2589. }
  2590. InternalRenderTask.prototype = {
  2591. initalizeGraphics:
  2592. function InternalRenderTask_initalizeGraphics(transparency) {
  2593. if (this.cancelled) {
  2594. return;
  2595. }
  2596. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2597. globalScope.StepperManager.enabled) {
  2598. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2599. this.stepper.init(this.operatorList);
  2600. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2601. }
  2602. var params = this.params;
  2603. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2604. this.objs, params.imageLayer);
  2605. this.gfx.beginDrawing(params.viewport, transparency);
  2606. this.operatorListIdx = 0;
  2607. this.graphicsReady = true;
  2608. if (this.graphicsReadyCallback) {
  2609. this.graphicsReadyCallback();
  2610. }
  2611. },
  2612. cancel: function InternalRenderTask_cancel() {
  2613. this.running = false;
  2614. this.cancelled = true;
  2615. this.callback('cancelled');
  2616. },
  2617. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2618. if (!this.graphicsReady) {
  2619. if (!this.graphicsReadyCallback) {
  2620. this.graphicsReadyCallback = this._continueBound;
  2621. }
  2622. return;
  2623. }
  2624. if (this.stepper) {
  2625. this.stepper.updateOperatorList(this.operatorList);
  2626. }
  2627. if (this.running) {
  2628. return;
  2629. }
  2630. this._continue();
  2631. },
  2632. _continue: function InternalRenderTask__continue() {
  2633. this.running = true;
  2634. if (this.cancelled) {
  2635. return;
  2636. }
  2637. if (this.params.continueCallback) {
  2638. this.params.continueCallback(this._scheduleNextBound);
  2639. } else {
  2640. this._scheduleNext();
  2641. }
  2642. },
  2643. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2644. window.requestAnimationFrame(this._nextBound);
  2645. },
  2646. _next: function InternalRenderTask__next() {
  2647. if (this.cancelled) {
  2648. return;
  2649. }
  2650. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2651. this.operatorListIdx,
  2652. this._continueBound,
  2653. this.stepper);
  2654. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2655. this.running = false;
  2656. if (this.operatorList.lastChunk) {
  2657. this.gfx.endDrawing();
  2658. this.callback();
  2659. }
  2660. }
  2661. }
  2662. };
  2663. return InternalRenderTask;
  2664. })();
  2665. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2666. function fixMetadata(meta) {
  2667. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2668. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2669. function(code, d1, d2, d3) {
  2670. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2671. });
  2672. var chars = '';
  2673. for (var i = 0; i < bytes.length; i += 2) {
  2674. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2675. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2676. code !== 38 && false ? String.fromCharCode(code) :
  2677. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2678. }
  2679. return '>' + chars;
  2680. });
  2681. }
  2682. function Metadata(meta) {
  2683. if (typeof meta === 'string') {
  2684. // Ghostscript produces invalid metadata
  2685. meta = fixMetadata(meta);
  2686. var parser = new DOMParser();
  2687. meta = parser.parseFromString(meta, 'application/xml');
  2688. } else if (!(meta instanceof Document)) {
  2689. error('Metadata: Invalid metadata object');
  2690. }
  2691. this.metaDocument = meta;
  2692. this.metadata = {};
  2693. this.parse();
  2694. }
  2695. Metadata.prototype = {
  2696. parse: function Metadata_parse() {
  2697. var doc = this.metaDocument;
  2698. var rdf = doc.documentElement;
  2699. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2700. rdf = rdf.firstChild;
  2701. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2702. rdf = rdf.nextSibling;
  2703. }
  2704. }
  2705. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2706. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2707. return;
  2708. }
  2709. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2710. for (i = 0, length = children.length; i < length; i++) {
  2711. desc = children[i];
  2712. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2713. continue;
  2714. }
  2715. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2716. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2717. entry = desc.childNodes[ii];
  2718. name = entry.nodeName.toLowerCase();
  2719. this.metadata[name] = entry.textContent.trim();
  2720. }
  2721. }
  2722. }
  2723. },
  2724. get: function Metadata_get(name) {
  2725. return this.metadata[name] || null;
  2726. },
  2727. has: function Metadata_has(name) {
  2728. return typeof this.metadata[name] !== 'undefined';
  2729. }
  2730. };
  2731. return Metadata;
  2732. })();
  2733. // <canvas> contexts store most of the state we need natively.
  2734. // However, PDF needs a bit more state, which we store here.
  2735. // Minimal font size that would be used during canvas fillText operations.
  2736. var MIN_FONT_SIZE = 16;
  2737. var MAX_GROUP_SIZE = 4096;
  2738. var COMPILE_TYPE3_GLYPHS = true;
  2739. function createScratchCanvas(width, height) {
  2740. var canvas = document.createElement('canvas');
  2741. canvas.width = width;
  2742. canvas.height = height;
  2743. return canvas;
  2744. }
  2745. function addContextCurrentTransform(ctx) {
  2746. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  2747. if (!ctx.mozCurrentTransform) {
  2748. // Store the original context
  2749. ctx._scaleX = ctx._scaleX || 1.0;
  2750. ctx._scaleY = ctx._scaleY || 1.0;
  2751. ctx._originalSave = ctx.save;
  2752. ctx._originalRestore = ctx.restore;
  2753. ctx._originalRotate = ctx.rotate;
  2754. ctx._originalScale = ctx.scale;
  2755. ctx._originalTranslate = ctx.translate;
  2756. ctx._originalTransform = ctx.transform;
  2757. ctx._originalSetTransform = ctx.setTransform;
  2758. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  2759. ctx._transformStack = [];
  2760. Object.defineProperty(ctx, 'mozCurrentTransform', {
  2761. get: function getCurrentTransform() {
  2762. return this._transformMatrix;
  2763. }
  2764. });
  2765. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  2766. get: function getCurrentTransformInverse() {
  2767. // Calculation done using WolframAlpha:
  2768. // http://www.wolframalpha.com/input/?
  2769. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  2770. var m = this._transformMatrix;
  2771. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  2772. var ad_bc = a * d - b * c;
  2773. var bc_ad = b * c - a * d;
  2774. return [
  2775. d / ad_bc,
  2776. b / bc_ad,
  2777. c / bc_ad,
  2778. a / ad_bc,
  2779. (d * e - c * f) / bc_ad,
  2780. (b * e - a * f) / ad_bc
  2781. ];
  2782. }
  2783. });
  2784. ctx.save = function ctxSave() {
  2785. var old = this._transformMatrix;
  2786. this._transformStack.push(old);
  2787. this._transformMatrix = old.slice(0, 6);
  2788. this._originalSave();
  2789. };
  2790. ctx.restore = function ctxRestore() {
  2791. var prev = this._transformStack.pop();
  2792. if (prev) {
  2793. this._transformMatrix = prev;
  2794. this._originalRestore();
  2795. }
  2796. };
  2797. ctx.translate = function ctxTranslate(x, y) {
  2798. var m = this._transformMatrix;
  2799. m[4] = m[0] * x + m[2] * y + m[4];
  2800. m[5] = m[1] * x + m[3] * y + m[5];
  2801. this._originalTranslate(x, y);
  2802. };
  2803. ctx.scale = function ctxScale(x, y) {
  2804. var m = this._transformMatrix;
  2805. m[0] = m[0] * x;
  2806. m[1] = m[1] * x;
  2807. m[2] = m[2] * y;
  2808. m[3] = m[3] * y;
  2809. this._originalScale(x, y);
  2810. };
  2811. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  2812. var m = this._transformMatrix;
  2813. this._transformMatrix = [
  2814. m[0] * a + m[2] * b,
  2815. m[1] * a + m[3] * b,
  2816. m[0] * c + m[2] * d,
  2817. m[1] * c + m[3] * d,
  2818. m[0] * e + m[2] * f + m[4],
  2819. m[1] * e + m[3] * f + m[5]
  2820. ];
  2821. ctx._originalTransform(a, b, c, d, e, f);
  2822. };
  2823. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  2824. this._transformMatrix = [a, b, c, d, e, f];
  2825. ctx._originalSetTransform(a, b, c, d, e, f);
  2826. };
  2827. ctx.rotate = function ctxRotate(angle) {
  2828. var cosValue = Math.cos(angle);
  2829. var sinValue = Math.sin(angle);
  2830. var m = this._transformMatrix;
  2831. this._transformMatrix = [
  2832. m[0] * cosValue + m[2] * sinValue,
  2833. m[1] * cosValue + m[3] * sinValue,
  2834. m[0] * (-sinValue) + m[2] * cosValue,
  2835. m[1] * (-sinValue) + m[3] * cosValue,
  2836. m[4],
  2837. m[5]
  2838. ];
  2839. this._originalRotate(angle);
  2840. };
  2841. }
  2842. }
  2843. var CachedCanvases = (function CachedCanvasesClosure() {
  2844. var cache = {};
  2845. return {
  2846. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  2847. trackTransform) {
  2848. var canvasEntry;
  2849. if (id in cache) {
  2850. canvasEntry = cache[id];
  2851. canvasEntry.canvas.width = width;
  2852. canvasEntry.canvas.height = height;
  2853. // reset canvas transform for emulated mozCurrentTransform, if needed
  2854. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  2855. } else {
  2856. var canvas = createScratchCanvas(width, height);
  2857. var ctx = canvas.getContext('2d');
  2858. if (trackTransform) {
  2859. addContextCurrentTransform(ctx);
  2860. }
  2861. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  2862. }
  2863. return canvasEntry;
  2864. },
  2865. clear: function () {
  2866. for (var id in cache) {
  2867. var canvasEntry = cache[id];
  2868. // Zeroing the width and height causes Firefox to release graphics
  2869. // resources immediately, which can greatly reduce memory consumption.
  2870. canvasEntry.canvas.width = 0;
  2871. canvasEntry.canvas.height = 0;
  2872. delete cache[id];
  2873. }
  2874. }
  2875. };
  2876. })();
  2877. function compileType3Glyph(imgData) {
  2878. var POINT_TO_PROCESS_LIMIT = 1000;
  2879. var width = imgData.width, height = imgData.height;
  2880. var i, j, j0, width1 = width + 1;
  2881. var points = new Uint8Array(width1 * (height + 1));
  2882. var POINT_TYPES =
  2883. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  2884. // decodes bit-packed mask data
  2885. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  2886. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  2887. for (i = 0, ii = data0.length; i < ii; i++) {
  2888. var mask = 128, elem = data0[i];
  2889. while (mask > 0) {
  2890. data[pos++] = (elem & mask) ? 0 : 255;
  2891. mask >>= 1;
  2892. }
  2893. }
  2894. // finding iteresting points: every point is located between mask pixels,
  2895. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  2896. // will have flags assigned based on neighboring mask pixels:
  2897. // 4 | 8
  2898. // --P--
  2899. // 2 | 1
  2900. // We are interested only in points with the flags:
  2901. // - outside corners: 1, 2, 4, 8;
  2902. // - inside corners: 7, 11, 13, 14;
  2903. // - and, intersections: 5, 10.
  2904. var count = 0;
  2905. pos = 0;
  2906. if (data[pos] !== 0) {
  2907. points[0] = 1;
  2908. ++count;
  2909. }
  2910. for (j = 1; j < width; j++) {
  2911. if (data[pos] !== data[pos + 1]) {
  2912. points[j] = data[pos] ? 2 : 1;
  2913. ++count;
  2914. }
  2915. pos++;
  2916. }
  2917. if (data[pos] !== 0) {
  2918. points[j] = 2;
  2919. ++count;
  2920. }
  2921. for (i = 1; i < height; i++) {
  2922. pos = i * lineSize;
  2923. j0 = i * width1;
  2924. if (data[pos - lineSize] !== data[pos]) {
  2925. points[j0] = data[pos] ? 1 : 8;
  2926. ++count;
  2927. }
  2928. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  2929. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  2930. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  2931. for (j = 1; j < width; j++) {
  2932. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  2933. (data[pos - lineSize + 1] ? 8 : 0);
  2934. if (POINT_TYPES[sum]) {
  2935. points[j0 + j] = POINT_TYPES[sum];
  2936. ++count;
  2937. }
  2938. pos++;
  2939. }
  2940. if (data[pos - lineSize] !== data[pos]) {
  2941. points[j0 + j] = data[pos] ? 2 : 4;
  2942. ++count;
  2943. }
  2944. if (count > POINT_TO_PROCESS_LIMIT) {
  2945. return null;
  2946. }
  2947. }
  2948. pos = lineSize * (height - 1);
  2949. j0 = i * width1;
  2950. if (data[pos] !== 0) {
  2951. points[j0] = 8;
  2952. ++count;
  2953. }
  2954. for (j = 1; j < width; j++) {
  2955. if (data[pos] !== data[pos + 1]) {
  2956. points[j0 + j] = data[pos] ? 4 : 8;
  2957. ++count;
  2958. }
  2959. pos++;
  2960. }
  2961. if (data[pos] !== 0) {
  2962. points[j0 + j] = 4;
  2963. ++count;
  2964. }
  2965. if (count > POINT_TO_PROCESS_LIMIT) {
  2966. return null;
  2967. }
  2968. // building outlines
  2969. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  2970. var outlines = [];
  2971. for (i = 0; count && i <= height; i++) {
  2972. var p = i * width1;
  2973. var end = p + width;
  2974. while (p < end && !points[p]) {
  2975. p++;
  2976. }
  2977. if (p === end) {
  2978. continue;
  2979. }
  2980. var coords = [p % width1, i];
  2981. var type = points[p], p0 = p, pp;
  2982. do {
  2983. var step = steps[type];
  2984. do {
  2985. p += step;
  2986. } while (!points[p]);
  2987. pp = points[p];
  2988. if (pp !== 5 && pp !== 10) {
  2989. // set new direction
  2990. type = pp;
  2991. // delete mark
  2992. points[p] = 0;
  2993. } else { // type is 5 or 10, ie, a crossing
  2994. // set new direction
  2995. type = pp & ((0x33 * type) >> 4);
  2996. // set new type for "future hit"
  2997. points[p] &= (type >> 2 | type << 2);
  2998. }
  2999. coords.push(p % width1);
  3000. coords.push((p / width1) | 0);
  3001. --count;
  3002. } while (p0 !== p);
  3003. outlines.push(coords);
  3004. --i;
  3005. }
  3006. var drawOutline = function(c) {
  3007. c.save();
  3008. // the path shall be painted in [0..1]x[0..1] space
  3009. c.scale(1 / width, -1 / height);
  3010. c.translate(0, -height);
  3011. c.beginPath();
  3012. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3013. var o = outlines[i];
  3014. c.moveTo(o[0], o[1]);
  3015. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3016. c.lineTo(o[j], o[j+1]);
  3017. }
  3018. }
  3019. c.fill();
  3020. c.beginPath();
  3021. c.restore();
  3022. };
  3023. return drawOutline;
  3024. }
  3025. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3026. function CanvasExtraState(old) {
  3027. // Are soft masks and alpha values shapes or opacities?
  3028. this.alphaIsShape = false;
  3029. this.fontSize = 0;
  3030. this.fontSizeScale = 1;
  3031. this.textMatrix = IDENTITY_MATRIX;
  3032. this.textMatrixScale = 1;
  3033. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3034. this.leading = 0;
  3035. // Current point (in user coordinates)
  3036. this.x = 0;
  3037. this.y = 0;
  3038. // Start of text line (in text coordinates)
  3039. this.lineX = 0;
  3040. this.lineY = 0;
  3041. // Character and word spacing
  3042. this.charSpacing = 0;
  3043. this.wordSpacing = 0;
  3044. this.textHScale = 1;
  3045. this.textRenderingMode = TextRenderingMode.FILL;
  3046. this.textRise = 0;
  3047. // Default fore and background colors
  3048. this.fillColor = '#000000';
  3049. this.strokeColor = '#000000';
  3050. // Note: fill alpha applies to all non-stroking operations
  3051. this.fillAlpha = 1;
  3052. this.strokeAlpha = 1;
  3053. this.lineWidth = 1;
  3054. this.activeSMask = null; // nonclonable field (see the save method below)
  3055. this.old = old;
  3056. }
  3057. CanvasExtraState.prototype = {
  3058. clone: function CanvasExtraState_clone() {
  3059. return Object.create(this);
  3060. },
  3061. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3062. this.x = x;
  3063. this.y = y;
  3064. }
  3065. };
  3066. return CanvasExtraState;
  3067. })();
  3068. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3069. // Defines the time the executeOperatorList is going to be executing
  3070. // before it stops and shedules a continue of execution.
  3071. var EXECUTION_TIME = 15;
  3072. // Defines the number of steps before checking the execution time
  3073. var EXECUTION_STEPS = 10;
  3074. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3075. this.ctx = canvasCtx;
  3076. this.current = new CanvasExtraState();
  3077. this.stateStack = [];
  3078. this.pendingClip = null;
  3079. this.pendingEOFill = false;
  3080. this.res = null;
  3081. this.xobjs = null;
  3082. this.commonObjs = commonObjs;
  3083. this.objs = objs;
  3084. this.imageLayer = imageLayer;
  3085. this.groupStack = [];
  3086. this.processingType3 = null;
  3087. // Patterns are painted relative to the initial page/form transform, see pdf
  3088. // spec 8.7.2 NOTE 1.
  3089. this.baseTransform = null;
  3090. this.baseTransformStack = [];
  3091. this.groupLevel = 0;
  3092. this.smaskStack = [];
  3093. this.smaskCounter = 0;
  3094. this.tempSMask = null;
  3095. if (canvasCtx) {
  3096. addContextCurrentTransform(canvasCtx);
  3097. }
  3098. }
  3099. function putBinaryImageData(ctx, imgData) {
  3100. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3101. ctx.putImageData(imgData, 0, 0);
  3102. return;
  3103. }
  3104. // Put the image data to the canvas in chunks, rather than putting the
  3105. // whole image at once. This saves JS memory, because the ImageData object
  3106. // is smaller. It also possibly saves C++ memory within the implementation
  3107. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3108. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3109. // because too many putImageData() calls will slow things down.
  3110. //
  3111. // Note: as written, if the last chunk is partial, the putImageData() call
  3112. // will (conceptually) put pixels past the bounds of the canvas. But
  3113. // that's ok; any such pixels are ignored.
  3114. var height = imgData.height, width = imgData.width;
  3115. var fullChunkHeight = 16;
  3116. var fracChunks = height / fullChunkHeight;
  3117. var fullChunks = Math.floor(fracChunks);
  3118. var totalChunks = Math.ceil(fracChunks);
  3119. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3120. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3121. var srcPos = 0, destPos;
  3122. var src = imgData.data;
  3123. var dest = chunkImgData.data;
  3124. var i, j, thisChunkHeight, elemsInThisChunk;
  3125. // There are multiple forms in which the pixel data can be passed, and
  3126. // imgData.kind tells us which one this is.
  3127. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3128. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3129. var srcLength = src.byteLength;
  3130. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3131. new Uint32ArrayView(dest);
  3132. var dest32DataLength = dest32.length;
  3133. var fullSrcDiff = (width + 7) >> 3;
  3134. var white = 0xFFFFFFFF;
  3135. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3136. 0xFF000000 : 0x000000FF;
  3137. for (i = 0; i < totalChunks; i++) {
  3138. thisChunkHeight =
  3139. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3140. destPos = 0;
  3141. for (j = 0; j < thisChunkHeight; j++) {
  3142. var srcDiff = srcLength - srcPos;
  3143. var k = 0;
  3144. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3145. var kEndUnrolled = kEnd & ~7;
  3146. var mask = 0;
  3147. var srcByte = 0;
  3148. for (; k < kEndUnrolled; k += 8) {
  3149. srcByte = src[srcPos++];
  3150. dest32[destPos++] = (srcByte & 128) ? white : black;
  3151. dest32[destPos++] = (srcByte & 64) ? white : black;
  3152. dest32[destPos++] = (srcByte & 32) ? white : black;
  3153. dest32[destPos++] = (srcByte & 16) ? white : black;
  3154. dest32[destPos++] = (srcByte & 8) ? white : black;
  3155. dest32[destPos++] = (srcByte & 4) ? white : black;
  3156. dest32[destPos++] = (srcByte & 2) ? white : black;
  3157. dest32[destPos++] = (srcByte & 1) ? white : black;
  3158. }
  3159. for (; k < kEnd; k++) {
  3160. if (mask === 0) {
  3161. srcByte = src[srcPos++];
  3162. mask = 128;
  3163. }
  3164. dest32[destPos++] = (srcByte & mask) ? white : black;
  3165. mask >>= 1;
  3166. }
  3167. }
  3168. // We ran out of input. Make all remaining pixels transparent.
  3169. while (destPos < dest32DataLength) {
  3170. dest32[destPos++] = 0;
  3171. }
  3172. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3173. }
  3174. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3175. // RGBA, 32-bits per pixel.
  3176. j = 0;
  3177. elemsInThisChunk = width * fullChunkHeight * 4;
  3178. for (i = 0; i < fullChunks; i++) {
  3179. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3180. srcPos += elemsInThisChunk;
  3181. ctx.putImageData(chunkImgData, 0, j);
  3182. j += fullChunkHeight;
  3183. }
  3184. if (i < totalChunks) {
  3185. elemsInThisChunk = width * partialChunkHeight * 4;
  3186. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3187. ctx.putImageData(chunkImgData, 0, j);
  3188. }
  3189. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3190. // RGB, 24-bits per pixel.
  3191. thisChunkHeight = fullChunkHeight;
  3192. elemsInThisChunk = width * thisChunkHeight;
  3193. for (i = 0; i < totalChunks; i++) {
  3194. if (i >= fullChunks) {
  3195. thisChunkHeight =partialChunkHeight;
  3196. elemsInThisChunk = width * thisChunkHeight;
  3197. }
  3198. destPos = 0;
  3199. for (j = elemsInThisChunk; j--;) {
  3200. dest[destPos++] = src[srcPos++];
  3201. dest[destPos++] = src[srcPos++];
  3202. dest[destPos++] = src[srcPos++];
  3203. dest[destPos++] = 255;
  3204. }
  3205. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3206. }
  3207. } else {
  3208. error('bad image kind: ' + imgData.kind);
  3209. }
  3210. }
  3211. function putBinaryImageMask(ctx, imgData) {
  3212. var height = imgData.height, width = imgData.width;
  3213. var fullChunkHeight = 16;
  3214. var fracChunks = height / fullChunkHeight;
  3215. var fullChunks = Math.floor(fracChunks);
  3216. var totalChunks = Math.ceil(fracChunks);
  3217. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3218. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3219. var srcPos = 0;
  3220. var src = imgData.data;
  3221. var dest = chunkImgData.data;
  3222. for (var i = 0; i < totalChunks; i++) {
  3223. var thisChunkHeight =
  3224. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3225. // Expand the mask so it can be used by the canvas. Any required
  3226. // inversion has already been handled.
  3227. var destPos = 3; // alpha component offset
  3228. for (var j = 0; j < thisChunkHeight; j++) {
  3229. var mask = 0;
  3230. for (var k = 0; k < width; k++) {
  3231. if (!mask) {
  3232. var elem = src[srcPos++];
  3233. mask = 128;
  3234. }
  3235. dest[destPos] = (elem & mask) ? 0 : 255;
  3236. destPos += 4;
  3237. mask >>= 1;
  3238. }
  3239. }
  3240. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3241. }
  3242. }
  3243. function copyCtxState(sourceCtx, destCtx) {
  3244. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3245. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3246. 'globalCompositeOperation', 'font'];
  3247. for (var i = 0, ii = properties.length; i < ii; i++) {
  3248. var property = properties[i];
  3249. if (property in sourceCtx) {
  3250. destCtx[property] = sourceCtx[property];
  3251. }
  3252. }
  3253. if ('setLineDash' in sourceCtx) {
  3254. destCtx.setLineDash(sourceCtx.getLineDash());
  3255. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3256. } else if ('mozDash' in sourceCtx) {
  3257. destCtx.mozDash = sourceCtx.mozDash;
  3258. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3259. }
  3260. }
  3261. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3262. var length = bytes.length;
  3263. for (var i = 3; i < length; i += 4) {
  3264. var alpha = bytes[i];
  3265. if (alpha === 0) {
  3266. bytes[i - 3] = r0;
  3267. bytes[i - 2] = g0;
  3268. bytes[i - 1] = b0;
  3269. } else if (alpha < 255) {
  3270. var alpha_ = 255 - alpha;
  3271. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3272. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3273. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3274. }
  3275. }
  3276. }
  3277. function composeSMaskAlpha(maskData, layerData) {
  3278. var length = maskData.length;
  3279. var scale = 1 / 255;
  3280. for (var i = 3; i < length; i += 4) {
  3281. var alpha = maskData[i];
  3282. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3283. }
  3284. }
  3285. function composeSMaskLuminosity(maskData, layerData) {
  3286. var length = maskData.length;
  3287. for (var i = 3; i < length; i += 4) {
  3288. var y = ((maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3289. (maskData[i - 2] * 152) + // * 0.59 ....
  3290. (maskData[i - 1] * 28)) | 0; // * 0.11 ....
  3291. layerData[i] = (layerData[i] * y) >> 16;
  3292. }
  3293. }
  3294. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3295. subtype, backdrop) {
  3296. var hasBackdrop = !!backdrop;
  3297. var r0 = hasBackdrop ? backdrop[0] : 0;
  3298. var g0 = hasBackdrop ? backdrop[1] : 0;
  3299. var b0 = hasBackdrop ? backdrop[2] : 0;
  3300. var composeFn;
  3301. if (subtype === 'Luminosity') {
  3302. composeFn = composeSMaskLuminosity;
  3303. } else {
  3304. composeFn = composeSMaskAlpha;
  3305. }
  3306. // processing image in chunks to save memory
  3307. var PIXELS_TO_PROCESS = 65536;
  3308. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3309. for (var row = 0; row < height; row += chunkSize) {
  3310. var chunkHeight = Math.min(chunkSize, height - row);
  3311. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3312. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3313. if (hasBackdrop) {
  3314. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3315. }
  3316. composeFn(maskData.data, layerData.data);
  3317. maskCtx.putImageData(layerData, 0, row);
  3318. }
  3319. }
  3320. function composeSMask(ctx, smask, layerCtx) {
  3321. var mask = smask.canvas;
  3322. var maskCtx = smask.context;
  3323. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3324. smask.offsetX, smask.offsetY);
  3325. var backdrop = smask.backdrop || null;
  3326. if (WebGLUtils.isEnabled) {
  3327. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3328. {subtype: smask.subtype, backdrop: backdrop});
  3329. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3330. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3331. return;
  3332. }
  3333. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3334. smask.subtype, backdrop);
  3335. ctx.drawImage(mask, 0, 0);
  3336. }
  3337. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3338. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3339. var NORMAL_CLIP = {};
  3340. var EO_CLIP = {};
  3341. CanvasGraphics.prototype = {
  3342. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3343. // For pdfs that use blend modes we have to clear the canvas else certain
  3344. // blend modes can look wrong since we'd be blending with a white
  3345. // backdrop. The problem with a transparent backdrop though is we then
  3346. // don't get sub pixel anti aliasing on text, so we fill with white if
  3347. // we can.
  3348. var width = this.ctx.canvas.width;
  3349. var height = this.ctx.canvas.height;
  3350. if (transparency) {
  3351. this.ctx.clearRect(0, 0, width, height);
  3352. } else {
  3353. this.ctx.mozOpaque = true;
  3354. this.ctx.save();
  3355. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3356. this.ctx.fillRect(0, 0, width, height);
  3357. this.ctx.restore();
  3358. }
  3359. var transform = viewport.transform;
  3360. this.ctx.save();
  3361. this.ctx.transform.apply(this.ctx, transform);
  3362. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3363. if (this.imageLayer) {
  3364. this.imageLayer.beginLayout();
  3365. }
  3366. },
  3367. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3368. operatorList,
  3369. executionStartIdx, continueCallback,
  3370. stepper) {
  3371. var argsArray = operatorList.argsArray;
  3372. var fnArray = operatorList.fnArray;
  3373. var i = executionStartIdx || 0;
  3374. var argsArrayLen = argsArray.length;
  3375. // Sometimes the OperatorList to execute is empty.
  3376. if (argsArrayLen === i) {
  3377. return i;
  3378. }
  3379. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3380. typeof continueCallback === 'function');
  3381. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3382. var steps = 0;
  3383. var commonObjs = this.commonObjs;
  3384. var objs = this.objs;
  3385. var fnId;
  3386. while (true) {
  3387. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3388. stepper.breakIt(i, continueCallback);
  3389. return i;
  3390. }
  3391. fnId = fnArray[i];
  3392. if (fnId !== OPS.dependency) {
  3393. this[fnId].apply(this, argsArray[i]);
  3394. } else {
  3395. var deps = argsArray[i];
  3396. for (var n = 0, nn = deps.length; n < nn; n++) {
  3397. var depObjId = deps[n];
  3398. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3399. var objsPool = common ? commonObjs : objs;
  3400. // If the promise isn't resolved yet, add the continueCallback
  3401. // to the promise and bail out.
  3402. if (!objsPool.isResolved(depObjId)) {
  3403. objsPool.get(depObjId, continueCallback);
  3404. return i;
  3405. }
  3406. }
  3407. }
  3408. i++;
  3409. // If the entire operatorList was executed, stop as were done.
  3410. if (i === argsArrayLen) {
  3411. return i;
  3412. }
  3413. // If the execution took longer then a certain amount of time and
  3414. // `continueCallback` is specified, interrupt the execution.
  3415. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3416. if (Date.now() > endTime) {
  3417. continueCallback();
  3418. return i;
  3419. }
  3420. steps = 0;
  3421. }
  3422. // If the operatorList isn't executed completely yet OR the execution
  3423. // time was short enough, do another execution round.
  3424. }
  3425. },
  3426. endDrawing: function CanvasGraphics_endDrawing() {
  3427. this.ctx.restore();
  3428. CachedCanvases.clear();
  3429. WebGLUtils.clear();
  3430. if (this.imageLayer) {
  3431. this.imageLayer.endLayout();
  3432. }
  3433. },
  3434. // Graphics state
  3435. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3436. this.current.lineWidth = width;
  3437. this.ctx.lineWidth = width;
  3438. },
  3439. setLineCap: function CanvasGraphics_setLineCap(style) {
  3440. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3441. },
  3442. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3443. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3444. },
  3445. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3446. this.ctx.miterLimit = limit;
  3447. },
  3448. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3449. var ctx = this.ctx;
  3450. if ('setLineDash' in ctx) {
  3451. ctx.setLineDash(dashArray);
  3452. ctx.lineDashOffset = dashPhase;
  3453. } else {
  3454. ctx.mozDash = dashArray;
  3455. ctx.mozDashOffset = dashPhase;
  3456. }
  3457. },
  3458. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3459. // Maybe if we one day fully support color spaces this will be important
  3460. // for now we can ignore.
  3461. // TODO set rendering intent?
  3462. },
  3463. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3464. // There's no way to control this with canvas, but we can safely ignore.
  3465. // TODO set flatness?
  3466. },
  3467. setGState: function CanvasGraphics_setGState(states) {
  3468. for (var i = 0, ii = states.length; i < ii; i++) {
  3469. var state = states[i];
  3470. var key = state[0];
  3471. var value = state[1];
  3472. switch (key) {
  3473. case 'LW':
  3474. this.setLineWidth(value);
  3475. break;
  3476. case 'LC':
  3477. this.setLineCap(value);
  3478. break;
  3479. case 'LJ':
  3480. this.setLineJoin(value);
  3481. break;
  3482. case 'ML':
  3483. this.setMiterLimit(value);
  3484. break;
  3485. case 'D':
  3486. this.setDash(value[0], value[1]);
  3487. break;
  3488. case 'RI':
  3489. this.setRenderingIntent(value);
  3490. break;
  3491. case 'FL':
  3492. this.setFlatness(value);
  3493. break;
  3494. case 'Font':
  3495. this.setFont(value[0], value[1]);
  3496. break;
  3497. case 'CA':
  3498. this.current.strokeAlpha = state[1];
  3499. break;
  3500. case 'ca':
  3501. this.current.fillAlpha = state[1];
  3502. this.ctx.globalAlpha = state[1];
  3503. break;
  3504. case 'BM':
  3505. if (value && value.name && (value.name !== 'Normal')) {
  3506. var mode = value.name.replace(/([A-Z])/g,
  3507. function(c) {
  3508. return '-' + c.toLowerCase();
  3509. }
  3510. ).substring(1);
  3511. this.ctx.globalCompositeOperation = mode;
  3512. if (this.ctx.globalCompositeOperation !== mode) {
  3513. warn('globalCompositeOperation "' + mode +
  3514. '" is not supported');
  3515. }
  3516. } else {
  3517. this.ctx.globalCompositeOperation = 'source-over';
  3518. }
  3519. break;
  3520. case 'SMask':
  3521. if (this.current.activeSMask) {
  3522. this.endSMaskGroup();
  3523. }
  3524. this.current.activeSMask = value ? this.tempSMask : null;
  3525. if (this.current.activeSMask) {
  3526. this.beginSMaskGroup();
  3527. }
  3528. this.tempSMask = null;
  3529. break;
  3530. }
  3531. }
  3532. },
  3533. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3534. var activeSMask = this.current.activeSMask;
  3535. var drawnWidth = activeSMask.canvas.width;
  3536. var drawnHeight = activeSMask.canvas.height;
  3537. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3538. var scratchCanvas = CachedCanvases.getCanvas(
  3539. cacheId, drawnWidth, drawnHeight, true);
  3540. var currentCtx = this.ctx;
  3541. var currentTransform = currentCtx.mozCurrentTransform;
  3542. this.ctx.save();
  3543. var groupCtx = scratchCanvas.context;
  3544. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3545. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3546. groupCtx.transform.apply(groupCtx, currentTransform);
  3547. copyCtxState(currentCtx, groupCtx);
  3548. this.ctx = groupCtx;
  3549. this.setGState([
  3550. ['BM', 'Normal'],
  3551. ['ca', 1],
  3552. ['CA', 1]
  3553. ]);
  3554. this.groupStack.push(currentCtx);
  3555. this.groupLevel++;
  3556. },
  3557. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3558. var groupCtx = this.ctx;
  3559. this.groupLevel--;
  3560. this.ctx = this.groupStack.pop();
  3561. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3562. this.ctx.restore();
  3563. },
  3564. save: function CanvasGraphics_save() {
  3565. this.ctx.save();
  3566. var old = this.current;
  3567. this.stateStack.push(old);
  3568. this.current = old.clone();
  3569. this.current.activeSMask = null;
  3570. },
  3571. restore: function CanvasGraphics_restore() {
  3572. if (this.stateStack.length !== 0) {
  3573. if (this.current.activeSMask !== null) {
  3574. this.endSMaskGroup();
  3575. }
  3576. this.current = this.stateStack.pop();
  3577. this.ctx.restore();
  3578. }
  3579. },
  3580. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3581. this.ctx.transform(a, b, c, d, e, f);
  3582. },
  3583. // Path
  3584. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3585. var ctx = this.ctx;
  3586. var current = this.current;
  3587. var x = current.x, y = current.y;
  3588. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3589. switch (ops[i] | 0) {
  3590. case OPS.rectangle:
  3591. x = args[j++];
  3592. y = args[j++];
  3593. var width = args[j++];
  3594. var height = args[j++];
  3595. if (width === 0) {
  3596. width = this.getSinglePixelWidth();
  3597. }
  3598. if (height === 0) {
  3599. height = this.getSinglePixelWidth();
  3600. }
  3601. var xw = x + width;
  3602. var yh = y + height;
  3603. this.ctx.moveTo(x, y);
  3604. this.ctx.lineTo(xw, y);
  3605. this.ctx.lineTo(xw, yh);
  3606. this.ctx.lineTo(x, yh);
  3607. this.ctx.lineTo(x, y);
  3608. this.ctx.closePath();
  3609. break;
  3610. case OPS.moveTo:
  3611. x = args[j++];
  3612. y = args[j++];
  3613. ctx.moveTo(x, y);
  3614. break;
  3615. case OPS.lineTo:
  3616. x = args[j++];
  3617. y = args[j++];
  3618. ctx.lineTo(x, y);
  3619. break;
  3620. case OPS.curveTo:
  3621. x = args[j + 4];
  3622. y = args[j + 5];
  3623. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3624. x, y);
  3625. j += 6;
  3626. break;
  3627. case OPS.curveTo2:
  3628. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3629. args[j + 2], args[j + 3]);
  3630. x = args[j + 2];
  3631. y = args[j + 3];
  3632. j += 4;
  3633. break;
  3634. case OPS.curveTo3:
  3635. x = args[j + 2];
  3636. y = args[j + 3];
  3637. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3638. j += 4;
  3639. break;
  3640. case OPS.closePath:
  3641. ctx.closePath();
  3642. break;
  3643. }
  3644. }
  3645. current.setCurrentPoint(x, y);
  3646. },
  3647. closePath: function CanvasGraphics_closePath() {
  3648. this.ctx.closePath();
  3649. },
  3650. stroke: function CanvasGraphics_stroke(consumePath) {
  3651. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3652. var ctx = this.ctx;
  3653. var strokeColor = this.current.strokeColor;
  3654. if (this.current.lineWidth === 0) {
  3655. ctx.lineWidth = this.getSinglePixelWidth();
  3656. }
  3657. // For stroke we want to temporarily change the global alpha to the
  3658. // stroking alpha.
  3659. ctx.globalAlpha = this.current.strokeAlpha;
  3660. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3661. strokeColor.type === 'Pattern') {
  3662. // for patterns, we transform to pattern space, calculate
  3663. // the pattern, call stroke, and restore to user space
  3664. ctx.save();
  3665. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3666. ctx.stroke();
  3667. ctx.restore();
  3668. } else {
  3669. ctx.stroke();
  3670. }
  3671. if (consumePath) {
  3672. this.consumePath();
  3673. }
  3674. // Restore the global alpha to the fill alpha
  3675. ctx.globalAlpha = this.current.fillAlpha;
  3676. },
  3677. closeStroke: function CanvasGraphics_closeStroke() {
  3678. this.closePath();
  3679. this.stroke();
  3680. },
  3681. fill: function CanvasGraphics_fill(consumePath) {
  3682. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3683. var ctx = this.ctx;
  3684. var fillColor = this.current.fillColor;
  3685. var needRestore = false;
  3686. if (fillColor && fillColor.hasOwnProperty('type') &&
  3687. fillColor.type === 'Pattern') {
  3688. ctx.save();
  3689. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3690. needRestore = true;
  3691. }
  3692. if (this.pendingEOFill) {
  3693. if (ctx.mozFillRule !== undefined) {
  3694. ctx.mozFillRule = 'evenodd';
  3695. ctx.fill();
  3696. ctx.mozFillRule = 'nonzero';
  3697. } else {
  3698. try {
  3699. ctx.fill('evenodd');
  3700. } catch (ex) {
  3701. // shouldn't really happen, but browsers might think differently
  3702. ctx.fill();
  3703. }
  3704. }
  3705. this.pendingEOFill = false;
  3706. } else {
  3707. ctx.fill();
  3708. }
  3709. if (needRestore) {
  3710. ctx.restore();
  3711. }
  3712. if (consumePath) {
  3713. this.consumePath();
  3714. }
  3715. },
  3716. eoFill: function CanvasGraphics_eoFill() {
  3717. this.pendingEOFill = true;
  3718. this.fill();
  3719. },
  3720. fillStroke: function CanvasGraphics_fillStroke() {
  3721. this.fill(false);
  3722. this.stroke(false);
  3723. this.consumePath();
  3724. },
  3725. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3726. this.pendingEOFill = true;
  3727. this.fillStroke();
  3728. },
  3729. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3730. this.closePath();
  3731. this.fillStroke();
  3732. },
  3733. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3734. this.pendingEOFill = true;
  3735. this.closePath();
  3736. this.fillStroke();
  3737. },
  3738. endPath: function CanvasGraphics_endPath() {
  3739. this.consumePath();
  3740. },
  3741. // Clipping
  3742. clip: function CanvasGraphics_clip() {
  3743. this.pendingClip = NORMAL_CLIP;
  3744. },
  3745. eoClip: function CanvasGraphics_eoClip() {
  3746. this.pendingClip = EO_CLIP;
  3747. },
  3748. // Text
  3749. beginText: function CanvasGraphics_beginText() {
  3750. this.current.textMatrix = IDENTITY_MATRIX;
  3751. this.current.textMatrixScale = 1;
  3752. this.current.x = this.current.lineX = 0;
  3753. this.current.y = this.current.lineY = 0;
  3754. },
  3755. endText: function CanvasGraphics_endText() {
  3756. var paths = this.pendingTextPaths;
  3757. var ctx = this.ctx;
  3758. if (paths === undefined) {
  3759. ctx.beginPath();
  3760. return;
  3761. }
  3762. ctx.save();
  3763. ctx.beginPath();
  3764. for (var i = 0; i < paths.length; i++) {
  3765. var path = paths[i];
  3766. ctx.setTransform.apply(ctx, path.transform);
  3767. ctx.translate(path.x, path.y);
  3768. path.addToPath(ctx, path.fontSize);
  3769. }
  3770. ctx.restore();
  3771. ctx.clip();
  3772. ctx.beginPath();
  3773. delete this.pendingTextPaths;
  3774. },
  3775. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  3776. this.current.charSpacing = spacing;
  3777. },
  3778. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  3779. this.current.wordSpacing = spacing;
  3780. },
  3781. setHScale: function CanvasGraphics_setHScale(scale) {
  3782. this.current.textHScale = scale / 100;
  3783. },
  3784. setLeading: function CanvasGraphics_setLeading(leading) {
  3785. this.current.leading = -leading;
  3786. },
  3787. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  3788. var fontObj = this.commonObjs.get(fontRefName);
  3789. var current = this.current;
  3790. if (!fontObj) {
  3791. error('Can\'t find font for ' + fontRefName);
  3792. }
  3793. current.fontMatrix = (fontObj.fontMatrix ?
  3794. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3795. // A valid matrix needs all main diagonal elements to be non-zero
  3796. // This also ensures we bypass FF bugzilla bug #719844.
  3797. if (current.fontMatrix[0] === 0 ||
  3798. current.fontMatrix[3] === 0) {
  3799. warn('Invalid font matrix for font ' + fontRefName);
  3800. }
  3801. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  3802. // and in some docs this can be negative (inverted x-y axes).
  3803. if (size < 0) {
  3804. size = -size;
  3805. current.fontDirection = -1;
  3806. } else {
  3807. current.fontDirection = 1;
  3808. }
  3809. this.current.font = fontObj;
  3810. this.current.fontSize = size;
  3811. if (fontObj.isType3Font) {
  3812. return; // we don't need ctx.font for Type3 fonts
  3813. }
  3814. var name = fontObj.loadedName || 'sans-serif';
  3815. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3816. (fontObj.bold ? 'bold' : 'normal');
  3817. var italic = fontObj.italic ? 'italic' : 'normal';
  3818. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  3819. // Some font backends cannot handle fonts below certain size.
  3820. // Keeping the font at minimal size and using the fontSizeScale to change
  3821. // the current transformation matrix before the fillText/strokeText.
  3822. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  3823. var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
  3824. this.current.fontSizeScale = browserFontSize !== MIN_FONT_SIZE ? 1.0 :
  3825. size / MIN_FONT_SIZE;
  3826. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  3827. this.ctx.font = rule;
  3828. },
  3829. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  3830. this.current.textRenderingMode = mode;
  3831. },
  3832. setTextRise: function CanvasGraphics_setTextRise(rise) {
  3833. this.current.textRise = rise;
  3834. },
  3835. moveText: function CanvasGraphics_moveText(x, y) {
  3836. this.current.x = this.current.lineX += x;
  3837. this.current.y = this.current.lineY += y;
  3838. },
  3839. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  3840. this.setLeading(-y);
  3841. this.moveText(x, y);
  3842. },
  3843. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  3844. this.current.textMatrix = [a, b, c, d, e, f];
  3845. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  3846. this.current.x = this.current.lineX = 0;
  3847. this.current.y = this.current.lineY = 0;
  3848. },
  3849. nextLine: function CanvasGraphics_nextLine() {
  3850. this.moveText(0, this.current.leading);
  3851. },
  3852. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  3853. var ctx = this.ctx;
  3854. var current = this.current;
  3855. var font = current.font;
  3856. var textRenderingMode = current.textRenderingMode;
  3857. var fontSize = current.fontSize / current.fontSizeScale;
  3858. var fillStrokeMode = textRenderingMode &
  3859. TextRenderingMode.FILL_STROKE_MASK;
  3860. var isAddToPathSet = !!(textRenderingMode &
  3861. TextRenderingMode.ADD_TO_PATH_FLAG);
  3862. var addToPath;
  3863. if (font.disableFontFace || isAddToPathSet) {
  3864. addToPath = font.getPathGenerator(this.commonObjs, character);
  3865. }
  3866. if (font.disableFontFace) {
  3867. ctx.save();
  3868. ctx.translate(x, y);
  3869. ctx.beginPath();
  3870. addToPath(ctx, fontSize);
  3871. if (fillStrokeMode === TextRenderingMode.FILL ||
  3872. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3873. ctx.fill();
  3874. }
  3875. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3876. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3877. ctx.stroke();
  3878. }
  3879. ctx.restore();
  3880. } else {
  3881. if (fillStrokeMode === TextRenderingMode.FILL ||
  3882. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3883. ctx.fillText(character, x, y);
  3884. }
  3885. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3886. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3887. ctx.strokeText(character, x, y);
  3888. }
  3889. }
  3890. if (isAddToPathSet) {
  3891. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  3892. paths.push({
  3893. transform: ctx.mozCurrentTransform,
  3894. x: x,
  3895. y: y,
  3896. fontSize: fontSize,
  3897. addToPath: addToPath
  3898. });
  3899. }
  3900. },
  3901. get isFontSubpixelAAEnabled() {
  3902. // Checks if anti-aliasing is enabled when scaled text is painted.
  3903. // On Windows GDI scaled fonts looks bad.
  3904. var ctx = document.createElement('canvas').getContext('2d');
  3905. ctx.scale(1.5, 1);
  3906. ctx.fillText('I', 0, 10);
  3907. var data = ctx.getImageData(0, 0, 10, 10).data;
  3908. var enabled = false;
  3909. for (var i = 3; i < data.length; i += 4) {
  3910. if (data[i] > 0 && data[i] < 255) {
  3911. enabled = true;
  3912. break;
  3913. }
  3914. }
  3915. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  3916. },
  3917. showText: function CanvasGraphics_showText(glyphs) {
  3918. var current = this.current;
  3919. var font = current.font;
  3920. if (font.isType3Font) {
  3921. return this.showType3Text(glyphs);
  3922. }
  3923. var fontSize = current.fontSize;
  3924. if (fontSize === 0) {
  3925. return;
  3926. }
  3927. var ctx = this.ctx;
  3928. var fontSizeScale = current.fontSizeScale;
  3929. var charSpacing = current.charSpacing;
  3930. var wordSpacing = current.wordSpacing;
  3931. var fontDirection = current.fontDirection;
  3932. var textHScale = current.textHScale * fontDirection;
  3933. var glyphsLength = glyphs.length;
  3934. var vertical = font.vertical;
  3935. var defaultVMetrics = font.defaultVMetrics;
  3936. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3937. var simpleFillText =
  3938. current.textRenderingMode === TextRenderingMode.FILL &&
  3939. !font.disableFontFace;
  3940. ctx.save();
  3941. ctx.transform.apply(ctx, current.textMatrix);
  3942. ctx.translate(current.x, current.y + current.textRise);
  3943. if (fontDirection > 0) {
  3944. ctx.scale(textHScale, -1);
  3945. } else {
  3946. ctx.scale(textHScale, 1);
  3947. }
  3948. var lineWidth = current.lineWidth;
  3949. var scale = current.textMatrixScale;
  3950. if (scale === 0 || lineWidth === 0) {
  3951. lineWidth = this.getSinglePixelWidth();
  3952. } else {
  3953. lineWidth /= scale;
  3954. }
  3955. if (fontSizeScale !== 1.0) {
  3956. ctx.scale(fontSizeScale, fontSizeScale);
  3957. lineWidth /= fontSizeScale;
  3958. }
  3959. ctx.lineWidth = lineWidth;
  3960. var x = 0, i;
  3961. for (i = 0; i < glyphsLength; ++i) {
  3962. var glyph = glyphs[i];
  3963. if (glyph === null) {
  3964. // word break
  3965. x += fontDirection * wordSpacing;
  3966. continue;
  3967. } else if (isNum(glyph)) {
  3968. x += -glyph * fontSize * 0.001;
  3969. continue;
  3970. }
  3971. var restoreNeeded = false;
  3972. var character = glyph.fontChar;
  3973. var accent = glyph.accent;
  3974. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  3975. var width = glyph.width;
  3976. if (vertical) {
  3977. var vmetric, vx, vy;
  3978. vmetric = glyph.vmetric || defaultVMetrics;
  3979. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  3980. vx = -vx * widthAdvanceScale;
  3981. vy = vmetric[2] * widthAdvanceScale;
  3982. width = vmetric ? -vmetric[0] : width;
  3983. scaledX = vx / fontSizeScale;
  3984. scaledY = (x + vy) / fontSizeScale;
  3985. } else {
  3986. scaledX = x / fontSizeScale;
  3987. scaledY = 0;
  3988. }
  3989. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  3990. // some standard fonts may not have the exact width, trying to
  3991. // rescale per character
  3992. var measuredWidth = ctx.measureText(character).width * 1000 /
  3993. fontSize * fontSizeScale;
  3994. var characterScaleX = width / measuredWidth;
  3995. restoreNeeded = true;
  3996. ctx.save();
  3997. ctx.scale(characterScaleX, 1);
  3998. scaledX /= characterScaleX;
  3999. }
  4000. if (simpleFillText && !accent) {
  4001. // common case
  4002. ctx.fillText(character, scaledX, scaledY);
  4003. } else {
  4004. this.paintChar(character, scaledX, scaledY);
  4005. if (accent) {
  4006. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4007. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4008. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4009. }
  4010. }
  4011. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4012. x += charWidth;
  4013. if (restoreNeeded) {
  4014. ctx.restore();
  4015. }
  4016. }
  4017. if (vertical) {
  4018. current.y -= x * textHScale;
  4019. } else {
  4020. current.x += x * textHScale;
  4021. }
  4022. ctx.restore();
  4023. },
  4024. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4025. // Type3 fonts - each glyph is a "mini-PDF"
  4026. var ctx = this.ctx;
  4027. var current = this.current;
  4028. var font = current.font;
  4029. var fontSize = current.fontSize;
  4030. var fontDirection = current.fontDirection;
  4031. var charSpacing = current.charSpacing;
  4032. var wordSpacing = current.wordSpacing;
  4033. var textHScale = current.textHScale * fontDirection;
  4034. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4035. var glyphsLength = glyphs.length;
  4036. var i, glyph, width;
  4037. if (fontSize === 0) {
  4038. return;
  4039. }
  4040. ctx.save();
  4041. ctx.transform.apply(ctx, current.textMatrix);
  4042. ctx.translate(current.x, current.y);
  4043. ctx.scale(textHScale, 1);
  4044. for (i = 0; i < glyphsLength; ++i) {
  4045. glyph = glyphs[i];
  4046. if (glyph === null) {
  4047. // word break
  4048. this.ctx.translate(wordSpacing, 0);
  4049. current.x += wordSpacing * textHScale;
  4050. continue;
  4051. } else if (isNum(glyph)) {
  4052. var spacingLength = -glyph * 0.001 * fontSize;
  4053. this.ctx.translate(spacingLength, 0);
  4054. current.x += spacingLength * textHScale;
  4055. continue;
  4056. }
  4057. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4058. if (!operatorList) {
  4059. warn('Type3 character \"' + glyph.operatorListId +
  4060. '\" is not available');
  4061. continue;
  4062. }
  4063. this.processingType3 = glyph;
  4064. this.save();
  4065. ctx.scale(fontSize, fontSize);
  4066. ctx.transform.apply(ctx, fontMatrix);
  4067. this.executeOperatorList(operatorList);
  4068. this.restore();
  4069. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4070. width = ((transformed[0] * fontSize + charSpacing) * fontDirection);
  4071. ctx.translate(width, 0);
  4072. current.x += width * textHScale;
  4073. }
  4074. ctx.restore();
  4075. this.processingType3 = null;
  4076. },
  4077. // Type3 fonts
  4078. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4079. // We can safely ignore this since the width should be the same
  4080. // as the width in the Widths array.
  4081. },
  4082. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4083. yWidth,
  4084. llx,
  4085. lly,
  4086. urx,
  4087. ury) {
  4088. // TODO According to the spec we're also suppose to ignore any operators
  4089. // that set color or include images while processing this type3 font.
  4090. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4091. this.clip();
  4092. this.endPath();
  4093. },
  4094. // Color
  4095. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4096. var pattern;
  4097. if (IR[0] === 'TilingPattern') {
  4098. var color = IR[1];
  4099. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4100. this.commonObjs, this.baseTransform);
  4101. } else {
  4102. pattern = getShadingPatternFromIR(IR);
  4103. }
  4104. return pattern;
  4105. },
  4106. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4107. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4108. },
  4109. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4110. this.current.fillColor = this.getColorN_Pattern(arguments);
  4111. },
  4112. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4113. var color = Util.makeCssRgb(arguments);
  4114. this.ctx.strokeStyle = color;
  4115. this.current.strokeColor = color;
  4116. },
  4117. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4118. var color = Util.makeCssRgb(arguments);
  4119. this.ctx.fillStyle = color;
  4120. this.current.fillColor = color;
  4121. },
  4122. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4123. var ctx = this.ctx;
  4124. this.save();
  4125. var pattern = getShadingPatternFromIR(patternIR);
  4126. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4127. var inv = ctx.mozCurrentTransformInverse;
  4128. if (inv) {
  4129. var canvas = ctx.canvas;
  4130. var width = canvas.width;
  4131. var height = canvas.height;
  4132. var bl = Util.applyTransform([0, 0], inv);
  4133. var br = Util.applyTransform([0, height], inv);
  4134. var ul = Util.applyTransform([width, 0], inv);
  4135. var ur = Util.applyTransform([width, height], inv);
  4136. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4137. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4138. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4139. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4140. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4141. } else {
  4142. // HACK to draw the gradient onto an infinite rectangle.
  4143. // PDF gradients are drawn across the entire image while
  4144. // Canvas only allows gradients to be drawn in a rectangle
  4145. // The following bug should allow us to remove this.
  4146. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4147. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4148. }
  4149. this.restore();
  4150. },
  4151. // Images
  4152. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4153. error('Should not call beginInlineImage');
  4154. },
  4155. beginImageData: function CanvasGraphics_beginImageData() {
  4156. error('Should not call beginImageData');
  4157. },
  4158. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4159. bbox) {
  4160. this.save();
  4161. this.baseTransformStack.push(this.baseTransform);
  4162. if (isArray(matrix) && 6 === matrix.length) {
  4163. this.transform.apply(this, matrix);
  4164. }
  4165. this.baseTransform = this.ctx.mozCurrentTransform;
  4166. if (isArray(bbox) && 4 === bbox.length) {
  4167. var width = bbox[2] - bbox[0];
  4168. var height = bbox[3] - bbox[1];
  4169. this.ctx.rect(bbox[0], bbox[1], width, height);
  4170. this.clip();
  4171. this.endPath();
  4172. }
  4173. },
  4174. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4175. this.restore();
  4176. this.baseTransform = this.baseTransformStack.pop();
  4177. },
  4178. beginGroup: function CanvasGraphics_beginGroup(group) {
  4179. this.save();
  4180. var currentCtx = this.ctx;
  4181. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4182. // group results aren't usually that different and they even have tools
  4183. // that ignore this setting. Notes from Rik on implmenting:
  4184. // - When you encounter an transparency group, create a new canvas with
  4185. // the dimensions of the bbox
  4186. // - copy the content from the previous canvas to the new canvas
  4187. // - draw as usual
  4188. // - remove the backdrop alpha:
  4189. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4190. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4191. // backdrop
  4192. // - remove background color:
  4193. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4194. if (!group.isolated) {
  4195. info('TODO: Support non-isolated groups.');
  4196. }
  4197. // TODO knockout - supposedly possible with the clever use of compositing
  4198. // modes.
  4199. if (group.knockout) {
  4200. warn('Knockout groups not supported.');
  4201. }
  4202. var currentTransform = currentCtx.mozCurrentTransform;
  4203. if (group.matrix) {
  4204. currentCtx.transform.apply(currentCtx, group.matrix);
  4205. }
  4206. assert(group.bbox, 'Bounding box is required.');
  4207. // Based on the current transform figure out how big the bounding box
  4208. // will actually be.
  4209. var bounds = Util.getAxialAlignedBoundingBox(
  4210. group.bbox,
  4211. currentCtx.mozCurrentTransform);
  4212. // Clip the bounding box to the current canvas.
  4213. var canvasBounds = [0,
  4214. 0,
  4215. currentCtx.canvas.width,
  4216. currentCtx.canvas.height];
  4217. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4218. // Use ceil in case we're between sizes so we don't create canvas that is
  4219. // too small and make the canvas at least 1x1 pixels.
  4220. var offsetX = Math.floor(bounds[0]);
  4221. var offsetY = Math.floor(bounds[1]);
  4222. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4223. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4224. var scaleX = 1, scaleY = 1;
  4225. if (drawnWidth > MAX_GROUP_SIZE) {
  4226. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4227. drawnWidth = MAX_GROUP_SIZE;
  4228. }
  4229. if (drawnHeight > MAX_GROUP_SIZE) {
  4230. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4231. drawnHeight = MAX_GROUP_SIZE;
  4232. }
  4233. var cacheId = 'groupAt' + this.groupLevel;
  4234. if (group.smask) {
  4235. // Using two cache entries is case if masks are used one after another.
  4236. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4237. }
  4238. var scratchCanvas = CachedCanvases.getCanvas(
  4239. cacheId, drawnWidth, drawnHeight, true);
  4240. var groupCtx = scratchCanvas.context;
  4241. // Since we created a new canvas that is just the size of the bounding box
  4242. // we have to translate the group ctx.
  4243. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4244. groupCtx.translate(-offsetX, -offsetY);
  4245. groupCtx.transform.apply(groupCtx, currentTransform);
  4246. if (group.smask) {
  4247. // Saving state and cached mask to be used in setGState.
  4248. this.smaskStack.push({
  4249. canvas: scratchCanvas.canvas,
  4250. context: groupCtx,
  4251. offsetX: offsetX,
  4252. offsetY: offsetY,
  4253. scaleX: scaleX,
  4254. scaleY: scaleY,
  4255. subtype: group.smask.subtype,
  4256. backdrop: group.smask.backdrop
  4257. });
  4258. } else {
  4259. // Setup the current ctx so when the group is popped we draw it at the
  4260. // right location.
  4261. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4262. currentCtx.translate(offsetX, offsetY);
  4263. currentCtx.scale(scaleX, scaleY);
  4264. }
  4265. // The transparency group inherits all off the current graphics state
  4266. // except the blend mode, soft mask, and alpha constants.
  4267. copyCtxState(currentCtx, groupCtx);
  4268. this.ctx = groupCtx;
  4269. this.setGState([
  4270. ['BM', 'Normal'],
  4271. ['ca', 1],
  4272. ['CA', 1]
  4273. ]);
  4274. this.groupStack.push(currentCtx);
  4275. this.groupLevel++;
  4276. },
  4277. endGroup: function CanvasGraphics_endGroup(group) {
  4278. this.groupLevel--;
  4279. var groupCtx = this.ctx;
  4280. this.ctx = this.groupStack.pop();
  4281. // Turn off image smoothing to avoid sub pixel interpolation which can
  4282. // look kind of blurry for some pdfs.
  4283. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4284. this.ctx.imageSmoothingEnabled = false;
  4285. } else {
  4286. this.ctx.mozImageSmoothingEnabled = false;
  4287. }
  4288. if (group.smask) {
  4289. this.tempSMask = this.smaskStack.pop();
  4290. } else {
  4291. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4292. }
  4293. this.restore();
  4294. },
  4295. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4296. this.save();
  4297. this.current = new CanvasExtraState();
  4298. },
  4299. endAnnotations: function CanvasGraphics_endAnnotations() {
  4300. this.restore();
  4301. },
  4302. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4303. matrix) {
  4304. this.save();
  4305. if (isArray(rect) && 4 === rect.length) {
  4306. var width = rect[2] - rect[0];
  4307. var height = rect[3] - rect[1];
  4308. this.ctx.rect(rect[0], rect[1], width, height);
  4309. this.clip();
  4310. this.endPath();
  4311. }
  4312. this.transform.apply(this, transform);
  4313. this.transform.apply(this, matrix);
  4314. },
  4315. endAnnotation: function CanvasGraphics_endAnnotation() {
  4316. this.restore();
  4317. },
  4318. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4319. var domImage = this.objs.get(objId);
  4320. if (!domImage) {
  4321. warn('Dependent image isn\'t ready yet');
  4322. return;
  4323. }
  4324. this.save();
  4325. var ctx = this.ctx;
  4326. // scale the image to the unit square
  4327. ctx.scale(1 / w, -1 / h);
  4328. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4329. 0, -h, w, h);
  4330. if (this.imageLayer) {
  4331. var currentTransform = ctx.mozCurrentTransformInverse;
  4332. var position = this.getCanvasPosition(0, 0);
  4333. this.imageLayer.appendImage({
  4334. objId: objId,
  4335. left: position[0],
  4336. top: position[1],
  4337. width: w / currentTransform[0],
  4338. height: h / currentTransform[3]
  4339. });
  4340. }
  4341. this.restore();
  4342. },
  4343. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4344. var ctx = this.ctx;
  4345. var width = img.width, height = img.height;
  4346. var glyph = this.processingType3;
  4347. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  4348. var MAX_SIZE_TO_COMPILE = 1000;
  4349. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4350. glyph.compiled =
  4351. compileType3Glyph({data: img.data, width: width, height: height});
  4352. } else {
  4353. glyph.compiled = null;
  4354. }
  4355. }
  4356. if (glyph && glyph.compiled) {
  4357. glyph.compiled(ctx);
  4358. return;
  4359. }
  4360. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4361. var maskCtx = maskCanvas.context;
  4362. maskCtx.save();
  4363. putBinaryImageMask(maskCtx, img);
  4364. maskCtx.globalCompositeOperation = 'source-in';
  4365. var fillColor = this.current.fillColor;
  4366. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4367. fillColor.type === 'Pattern') ?
  4368. fillColor.getPattern(maskCtx, this) : fillColor;
  4369. maskCtx.fillRect(0, 0, width, height);
  4370. maskCtx.restore();
  4371. this.paintInlineImageXObject(maskCanvas.canvas);
  4372. },
  4373. paintImageMaskXObjectRepeat:
  4374. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4375. scaleY, positions) {
  4376. var width = imgData.width;
  4377. var height = imgData.height;
  4378. var ctx = this.ctx;
  4379. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4380. var maskCtx = maskCanvas.context;
  4381. maskCtx.save();
  4382. putBinaryImageMask(maskCtx, imgData);
  4383. maskCtx.globalCompositeOperation = 'source-in';
  4384. var fillColor = this.current.fillColor;
  4385. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4386. fillColor.type === 'Pattern') ?
  4387. fillColor.getPattern(maskCtx, this) : fillColor;
  4388. maskCtx.fillRect(0, 0, width, height);
  4389. maskCtx.restore();
  4390. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4391. ctx.save();
  4392. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4393. ctx.scale(1, -1);
  4394. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4395. 0, -1, 1, 1);
  4396. ctx.restore();
  4397. }
  4398. },
  4399. paintImageMaskXObjectGroup:
  4400. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4401. var ctx = this.ctx;
  4402. for (var i = 0, ii = images.length; i < ii; i++) {
  4403. var image = images[i];
  4404. var width = image.width, height = image.height;
  4405. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4406. var maskCtx = maskCanvas.context;
  4407. maskCtx.save();
  4408. putBinaryImageMask(maskCtx, image);
  4409. maskCtx.globalCompositeOperation = 'source-in';
  4410. var fillColor = this.current.fillColor;
  4411. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4412. fillColor.type === 'Pattern') ?
  4413. fillColor.getPattern(maskCtx, this) : fillColor;
  4414. maskCtx.fillRect(0, 0, width, height);
  4415. maskCtx.restore();
  4416. ctx.save();
  4417. ctx.transform.apply(ctx, image.transform);
  4418. ctx.scale(1, -1);
  4419. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4420. 0, -1, 1, 1);
  4421. ctx.restore();
  4422. }
  4423. },
  4424. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4425. var imgData = this.objs.get(objId);
  4426. if (!imgData) {
  4427. warn('Dependent image isn\'t ready yet');
  4428. return;
  4429. }
  4430. this.paintInlineImageXObject(imgData);
  4431. },
  4432. paintImageXObjectRepeat:
  4433. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4434. positions) {
  4435. var imgData = this.objs.get(objId);
  4436. if (!imgData) {
  4437. warn('Dependent image isn\'t ready yet');
  4438. return;
  4439. }
  4440. var width = imgData.width;
  4441. var height = imgData.height;
  4442. var map = [];
  4443. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4444. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4445. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4446. }
  4447. this.paintInlineImageXObjectGroup(imgData, map);
  4448. },
  4449. paintInlineImageXObject:
  4450. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4451. var width = imgData.width;
  4452. var height = imgData.height;
  4453. var ctx = this.ctx;
  4454. this.save();
  4455. // scale the image to the unit square
  4456. ctx.scale(1 / width, -1 / height);
  4457. var currentTransform = ctx.mozCurrentTransformInverse;
  4458. var a = currentTransform[0], b = currentTransform[1];
  4459. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4460. var c = currentTransform[2], d = currentTransform[3];
  4461. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4462. var imgToPaint, tmpCanvas;
  4463. // instanceof HTMLElement does not work in jsdom node.js module
  4464. if (imgData instanceof HTMLElement || !imgData.data) {
  4465. imgToPaint = imgData;
  4466. } else {
  4467. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4468. var tmpCtx = tmpCanvas.context;
  4469. putBinaryImageData(tmpCtx, imgData);
  4470. imgToPaint = tmpCanvas.canvas;
  4471. }
  4472. var paintWidth = width, paintHeight = height;
  4473. var tmpCanvasId = 'prescale1';
  4474. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4475. // pixels during drawImage operation, painting on the temporary canvas(es)
  4476. // that are twice smaller in size
  4477. while ((widthScale > 2 && paintWidth > 1) ||
  4478. (heightScale > 2 && paintHeight > 1)) {
  4479. var newWidth = paintWidth, newHeight = paintHeight;
  4480. if (widthScale > 2 && paintWidth > 1) {
  4481. newWidth = Math.ceil(paintWidth / 2);
  4482. widthScale /= paintWidth / newWidth;
  4483. }
  4484. if (heightScale > 2 && paintHeight > 1) {
  4485. newHeight = Math.ceil(paintHeight / 2);
  4486. heightScale /= paintHeight / newHeight;
  4487. }
  4488. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4489. tmpCtx = tmpCanvas.context;
  4490. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4491. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4492. 0, 0, newWidth, newHeight);
  4493. imgToPaint = tmpCanvas.canvas;
  4494. paintWidth = newWidth;
  4495. paintHeight = newHeight;
  4496. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4497. }
  4498. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4499. 0, -height, width, height);
  4500. if (this.imageLayer) {
  4501. var position = this.getCanvasPosition(0, -height);
  4502. this.imageLayer.appendImage({
  4503. imgData: imgData,
  4504. left: position[0],
  4505. top: position[1],
  4506. width: width / currentTransform[0],
  4507. height: height / currentTransform[3]
  4508. });
  4509. }
  4510. this.restore();
  4511. },
  4512. paintInlineImageXObjectGroup:
  4513. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4514. var ctx = this.ctx;
  4515. var w = imgData.width;
  4516. var h = imgData.height;
  4517. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4518. var tmpCtx = tmpCanvas.context;
  4519. putBinaryImageData(tmpCtx, imgData);
  4520. for (var i = 0, ii = map.length; i < ii; i++) {
  4521. var entry = map[i];
  4522. ctx.save();
  4523. ctx.transform.apply(ctx, entry.transform);
  4524. ctx.scale(1, -1);
  4525. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4526. 0, -1, 1, 1);
  4527. if (this.imageLayer) {
  4528. var position = this.getCanvasPosition(entry.x, entry.y);
  4529. this.imageLayer.appendImage({
  4530. imgData: imgData,
  4531. left: position[0],
  4532. top: position[1],
  4533. width: w,
  4534. height: h
  4535. });
  4536. }
  4537. ctx.restore();
  4538. }
  4539. },
  4540. paintSolidColorImageMask:
  4541. function CanvasGraphics_paintSolidColorImageMask() {
  4542. this.ctx.fillRect(0, 0, 1, 1);
  4543. },
  4544. // Marked content
  4545. markPoint: function CanvasGraphics_markPoint(tag) {
  4546. // TODO Marked content.
  4547. },
  4548. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4549. // TODO Marked content.
  4550. },
  4551. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4552. // TODO Marked content.
  4553. },
  4554. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4555. tag, properties) {
  4556. // TODO Marked content.
  4557. },
  4558. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4559. // TODO Marked content.
  4560. },
  4561. // Compatibility
  4562. beginCompat: function CanvasGraphics_beginCompat() {
  4563. // TODO ignore undefined operators (should we do that anyway?)
  4564. },
  4565. endCompat: function CanvasGraphics_endCompat() {
  4566. // TODO stop ignoring undefined operators
  4567. },
  4568. // Helper functions
  4569. consumePath: function CanvasGraphics_consumePath() {
  4570. var ctx = this.ctx;
  4571. if (this.pendingClip) {
  4572. if (this.pendingClip === EO_CLIP) {
  4573. if (ctx.mozFillRule !== undefined) {
  4574. ctx.mozFillRule = 'evenodd';
  4575. ctx.clip();
  4576. ctx.mozFillRule = 'nonzero';
  4577. } else {
  4578. try {
  4579. ctx.clip('evenodd');
  4580. } catch (ex) {
  4581. // shouldn't really happen, but browsers might think differently
  4582. ctx.clip();
  4583. }
  4584. }
  4585. } else {
  4586. ctx.clip();
  4587. }
  4588. this.pendingClip = null;
  4589. }
  4590. ctx.beginPath();
  4591. },
  4592. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4593. var inverse = this.ctx.mozCurrentTransformInverse;
  4594. // max of the current horizontal and vertical scale
  4595. return Math.sqrt(Math.max(
  4596. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4597. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4598. },
  4599. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4600. var transform = this.ctx.mozCurrentTransform;
  4601. return [
  4602. transform[0] * x + transform[2] * y + transform[4],
  4603. transform[1] * x + transform[3] * y + transform[5]
  4604. ];
  4605. }
  4606. };
  4607. for (var op in OPS) {
  4608. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4609. }
  4610. return CanvasGraphics;
  4611. })();
  4612. var WebGLUtils = (function WebGLUtilsClosure() {
  4613. function loadShader(gl, code, shaderType) {
  4614. var shader = gl.createShader(shaderType);
  4615. gl.shaderSource(shader, code);
  4616. gl.compileShader(shader);
  4617. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4618. if (!compiled) {
  4619. var errorMsg = gl.getShaderInfoLog(shader);
  4620. throw new Error('Error during shader compilation: ' + errorMsg);
  4621. }
  4622. return shader;
  4623. }
  4624. function createVertexShader(gl, code) {
  4625. return loadShader(gl, code, gl.VERTEX_SHADER);
  4626. }
  4627. function createFragmentShader(gl, code) {
  4628. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4629. }
  4630. function createProgram(gl, shaders) {
  4631. var program = gl.createProgram();
  4632. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4633. gl.attachShader(program, shaders[i]);
  4634. }
  4635. gl.linkProgram(program);
  4636. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4637. if (!linked) {
  4638. var errorMsg = gl.getProgramInfoLog(program);
  4639. throw new Error('Error during program linking: ' + errorMsg);
  4640. }
  4641. return program;
  4642. }
  4643. function createTexture(gl, image, textureId) {
  4644. gl.activeTexture(textureId);
  4645. var texture = gl.createTexture();
  4646. gl.bindTexture(gl.TEXTURE_2D, texture);
  4647. // Set the parameters so we can render any size image.
  4648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4650. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4651. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4652. // Upload the image into the texture.
  4653. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4654. return texture;
  4655. }
  4656. var currentGL, currentCanvas;
  4657. function generageGL() {
  4658. if (currentGL) {
  4659. return;
  4660. }
  4661. currentCanvas = document.createElement('canvas');
  4662. currentGL = currentCanvas.getContext('webgl',
  4663. { premultipliedalpha: false });
  4664. }
  4665. var smaskVertexShaderCode = '\
  4666. attribute vec2 a_position; \
  4667. attribute vec2 a_texCoord; \
  4668. \
  4669. uniform vec2 u_resolution; \
  4670. \
  4671. varying vec2 v_texCoord; \
  4672. \
  4673. void main() { \
  4674. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4675. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4676. \
  4677. v_texCoord = a_texCoord; \
  4678. } ';
  4679. var smaskFragmentShaderCode = '\
  4680. precision mediump float; \
  4681. \
  4682. uniform vec4 u_backdrop; \
  4683. uniform int u_subtype; \
  4684. uniform sampler2D u_image; \
  4685. uniform sampler2D u_mask; \
  4686. \
  4687. varying vec2 v_texCoord; \
  4688. \
  4689. void main() { \
  4690. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4691. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4692. if (u_backdrop.a > 0.0) { \
  4693. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4694. u_backdrop.rgb * (1.0 - maskColor.a); \
  4695. } \
  4696. float lum; \
  4697. if (u_subtype == 0) { \
  4698. lum = maskColor.a; \
  4699. } else { \
  4700. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4701. maskColor.b * 0.11; \
  4702. } \
  4703. imageColor.a *= lum; \
  4704. imageColor.rgb *= imageColor.a; \
  4705. gl_FragColor = imageColor; \
  4706. } ';
  4707. var smaskCache = null;
  4708. function initSmaskGL() {
  4709. var canvas, gl;
  4710. generageGL();
  4711. canvas = currentCanvas;
  4712. currentCanvas = null;
  4713. gl = currentGL;
  4714. currentGL = null;
  4715. // setup a GLSL program
  4716. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4717. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4718. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4719. gl.useProgram(program);
  4720. var cache = {};
  4721. cache.gl = gl;
  4722. cache.canvas = canvas;
  4723. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4724. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4725. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4726. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4727. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4728. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4729. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4730. // provide texture coordinates for the rectangle.
  4731. var texCoordBuffer = gl.createBuffer();
  4732. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4733. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4734. 0.0, 0.0,
  4735. 1.0, 0.0,
  4736. 0.0, 1.0,
  4737. 0.0, 1.0,
  4738. 1.0, 0.0,
  4739. 1.0, 1.0]), gl.STATIC_DRAW);
  4740. gl.enableVertexAttribArray(texCoordLocation);
  4741. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4742. gl.uniform1i(texLayerLocation, 0);
  4743. gl.uniform1i(texMaskLocation, 1);
  4744. smaskCache = cache;
  4745. }
  4746. function composeSMask(layer, mask, properties) {
  4747. var width = layer.width, height = layer.height;
  4748. if (!smaskCache) {
  4749. initSmaskGL();
  4750. }
  4751. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4752. canvas.width = width;
  4753. canvas.height = height;
  4754. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4755. gl.uniform2f(cache.resolutionLocation, width, height);
  4756. if (properties.backdrop) {
  4757. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4758. properties.backdrop[1], properties.backdrop[2], 1);
  4759. } else {
  4760. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4761. }
  4762. gl.uniform1i(cache.subtypeLocation,
  4763. properties.subtype === 'Luminosity' ? 1 : 0);
  4764. // Create a textures
  4765. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4766. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4767. // Create a buffer and put a single clipspace rectangle in
  4768. // it (2 triangles)
  4769. var buffer = gl.createBuffer();
  4770. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4771. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4772. 0, 0,
  4773. width, 0,
  4774. 0, height,
  4775. 0, height,
  4776. width, 0,
  4777. width, height]), gl.STATIC_DRAW);
  4778. gl.enableVertexAttribArray(cache.positionLocation);
  4779. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4780. // draw
  4781. gl.clearColor(0, 0, 0, 0);
  4782. gl.enable(gl.BLEND);
  4783. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4784. gl.clear(gl.COLOR_BUFFER_BIT);
  4785. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4786. gl.flush();
  4787. gl.deleteTexture(texture);
  4788. gl.deleteTexture(maskTexture);
  4789. gl.deleteBuffer(buffer);
  4790. return canvas;
  4791. }
  4792. var figuresVertexShaderCode = '\
  4793. attribute vec2 a_position; \
  4794. attribute vec3 a_color; \
  4795. \
  4796. uniform vec2 u_resolution; \
  4797. uniform vec2 u_scale; \
  4798. uniform vec2 u_offset; \
  4799. \
  4800. varying vec4 v_color; \
  4801. \
  4802. void main() { \
  4803. vec2 position = (a_position + u_offset) * u_scale; \
  4804. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  4805. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4806. \
  4807. v_color = vec4(a_color / 255.0, 1.0); \
  4808. } ';
  4809. var figuresFragmentShaderCode = '\
  4810. precision mediump float; \
  4811. \
  4812. varying vec4 v_color; \
  4813. \
  4814. void main() { \
  4815. gl_FragColor = v_color; \
  4816. } ';
  4817. var figuresCache = null;
  4818. function initFiguresGL() {
  4819. var canvas, gl;
  4820. generageGL();
  4821. canvas = currentCanvas;
  4822. currentCanvas = null;
  4823. gl = currentGL;
  4824. currentGL = null;
  4825. // setup a GLSL program
  4826. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  4827. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  4828. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4829. gl.useProgram(program);
  4830. var cache = {};
  4831. cache.gl = gl;
  4832. cache.canvas = canvas;
  4833. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4834. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  4835. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  4836. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4837. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  4838. figuresCache = cache;
  4839. }
  4840. function drawFigures(width, height, backgroundColor, figures, context) {
  4841. if (!figuresCache) {
  4842. initFiguresGL();
  4843. }
  4844. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  4845. canvas.width = width;
  4846. canvas.height = height;
  4847. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4848. gl.uniform2f(cache.resolutionLocation, width, height);
  4849. // count triangle points
  4850. var count = 0;
  4851. var i, ii, rows;
  4852. for (i = 0, ii = figures.length; i < ii; i++) {
  4853. switch (figures[i].type) {
  4854. case 'lattice':
  4855. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  4856. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  4857. break;
  4858. case 'triangles':
  4859. count += figures[i].coords.length;
  4860. break;
  4861. }
  4862. }
  4863. // transfer data
  4864. var coords = new Float32Array(count * 2);
  4865. var colors = new Uint8Array(count * 3);
  4866. var coordsMap = context.coords, colorsMap = context.colors;
  4867. var pIndex = 0, cIndex = 0;
  4868. for (i = 0, ii = figures.length; i < ii; i++) {
  4869. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  4870. switch (figure.type) {
  4871. case 'lattice':
  4872. var cols = figure.verticesPerRow;
  4873. rows = (ps.length / cols) | 0;
  4874. for (var row = 1; row < rows; row++) {
  4875. var offset = row * cols + 1;
  4876. for (var col = 1; col < cols; col++, offset++) {
  4877. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  4878. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  4879. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  4880. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  4881. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  4882. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  4883. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  4884. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  4885. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  4886. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  4887. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  4888. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  4889. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  4890. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  4891. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  4892. coords[pIndex + 6] = coords[pIndex + 2];
  4893. coords[pIndex + 7] = coords[pIndex + 3];
  4894. coords[pIndex + 8] = coords[pIndex + 4];
  4895. coords[pIndex + 9] = coords[pIndex + 5];
  4896. coords[pIndex + 10] = coordsMap[ps[offset]];
  4897. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  4898. colors[cIndex + 9] = colors[cIndex + 3];
  4899. colors[cIndex + 10] = colors[cIndex + 4];
  4900. colors[cIndex + 11] = colors[cIndex + 5];
  4901. colors[cIndex + 12] = colors[cIndex + 6];
  4902. colors[cIndex + 13] = colors[cIndex + 7];
  4903. colors[cIndex + 14] = colors[cIndex + 8];
  4904. colors[cIndex + 15] = colorsMap[cs[offset]];
  4905. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  4906. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  4907. pIndex += 12;
  4908. cIndex += 18;
  4909. }
  4910. }
  4911. break;
  4912. case 'triangles':
  4913. for (var j = 0, jj = ps.length; j < jj; j++) {
  4914. coords[pIndex] = coordsMap[ps[j]];
  4915. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  4916. colors[cIndex] = colorsMap[cs[i]];
  4917. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  4918. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  4919. pIndex += 2;
  4920. cIndex += 3;
  4921. }
  4922. break;
  4923. }
  4924. }
  4925. // draw
  4926. if (backgroundColor) {
  4927. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  4928. backgroundColor[2] / 255, 1.0);
  4929. } else {
  4930. gl.clearColor(0, 0, 0, 0);
  4931. }
  4932. gl.clear(gl.COLOR_BUFFER_BIT);
  4933. var coordsBuffer = gl.createBuffer();
  4934. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  4935. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  4936. gl.enableVertexAttribArray(cache.positionLocation);
  4937. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4938. var colorsBuffer = gl.createBuffer();
  4939. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  4940. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  4941. gl.enableVertexAttribArray(cache.colorLocation);
  4942. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  4943. 0, 0);
  4944. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  4945. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  4946. gl.drawArrays(gl.TRIANGLES, 0, count);
  4947. gl.flush();
  4948. gl.deleteBuffer(coordsBuffer);
  4949. gl.deleteBuffer(colorsBuffer);
  4950. return canvas;
  4951. }
  4952. function cleanup() {
  4953. if (smaskCache && smaskCache.canvas) {
  4954. smaskCache.canvas.width = 0;
  4955. smaskCache.canvas.height = 0;
  4956. }
  4957. if (figuresCache && figuresCache.canvas) {
  4958. figuresCache.canvas.width = 0;
  4959. figuresCache.canvas.height = 0;
  4960. }
  4961. smaskCache = null;
  4962. figuresCache = null;
  4963. }
  4964. return {
  4965. get isEnabled() {
  4966. if (PDFJS.disableWebGL) {
  4967. return false;
  4968. }
  4969. var enabled = false;
  4970. try {
  4971. generageGL();
  4972. enabled = !!currentGL;
  4973. } catch (e) { }
  4974. return shadow(this, 'isEnabled', enabled);
  4975. },
  4976. composeSMask: composeSMask,
  4977. drawFigures: drawFigures,
  4978. clear: cleanup
  4979. };
  4980. })();
  4981. var ShadingIRs = {};
  4982. ShadingIRs.RadialAxial = {
  4983. fromIR: function RadialAxial_fromIR(raw) {
  4984. var type = raw[1];
  4985. var colorStops = raw[2];
  4986. var p0 = raw[3];
  4987. var p1 = raw[4];
  4988. var r0 = raw[5];
  4989. var r1 = raw[6];
  4990. return {
  4991. type: 'Pattern',
  4992. getPattern: function RadialAxial_getPattern(ctx) {
  4993. var grad;
  4994. if (type === 'axial') {
  4995. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  4996. } else if (type === 'radial') {
  4997. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  4998. }
  4999. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5000. var c = colorStops[i];
  5001. grad.addColorStop(c[0], c[1]);
  5002. }
  5003. return grad;
  5004. }
  5005. };
  5006. }
  5007. };
  5008. var createMeshCanvas = (function createMeshCanvasClosure() {
  5009. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5010. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5011. var coords = context.coords, colors = context.colors;
  5012. var bytes = data.data, rowSize = data.width * 4;
  5013. var tmp;
  5014. if (coords[p1 + 1] > coords[p2 + 1]) {
  5015. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5016. }
  5017. if (coords[p2 + 1] > coords[p3 + 1]) {
  5018. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5019. }
  5020. if (coords[p1 + 1] > coords[p2 + 1]) {
  5021. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5022. }
  5023. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5024. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5025. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5026. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5027. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5028. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5029. if (y1 >= y3) {
  5030. return;
  5031. }
  5032. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5033. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5034. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5035. var minY = Math.round(y1), maxY = Math.round(y3);
  5036. var xa, car, cag, cab;
  5037. var xb, cbr, cbg, cbb;
  5038. var k;
  5039. for (var y = minY; y <= maxY; y++) {
  5040. if (y < y2) {
  5041. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5042. xa = x1 - (x1 - x2) * k;
  5043. car = c1r - (c1r - c2r) * k;
  5044. cag = c1g - (c1g - c2g) * k;
  5045. cab = c1b - (c1b - c2b) * k;
  5046. } else {
  5047. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5048. xa = x2 - (x2 - x3) * k;
  5049. car = c2r - (c2r - c3r) * k;
  5050. cag = c2g - (c2g - c3g) * k;
  5051. cab = c2b - (c2b - c3b) * k;
  5052. }
  5053. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5054. xb = x1 - (x1 - x3) * k;
  5055. cbr = c1r - (c1r - c3r) * k;
  5056. cbg = c1g - (c1g - c3g) * k;
  5057. cbb = c1b - (c1b - c3b) * k;
  5058. var x1_ = Math.round(Math.min(xa, xb));
  5059. var x2_ = Math.round(Math.max(xa, xb));
  5060. var j = rowSize * y + x1_ * 4;
  5061. for (var x = x1_; x <= x2_; x++) {
  5062. k = (xa - x) / (xa - xb);
  5063. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5064. bytes[j++] = (car - (car - cbr) * k) | 0;
  5065. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5066. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5067. bytes[j++] = 255;
  5068. }
  5069. }
  5070. }
  5071. function drawFigure(data, figure, context) {
  5072. var ps = figure.coords;
  5073. var cs = figure.colors;
  5074. var i, ii;
  5075. switch (figure.type) {
  5076. case 'lattice':
  5077. var verticesPerRow = figure.verticesPerRow;
  5078. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5079. var cols = verticesPerRow - 1;
  5080. for (i = 0; i < rows; i++) {
  5081. var q = i * verticesPerRow;
  5082. for (var j = 0; j < cols; j++, q++) {
  5083. drawTriangle(data, context,
  5084. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5085. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5086. drawTriangle(data, context,
  5087. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5088. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5089. }
  5090. }
  5091. break;
  5092. case 'triangles':
  5093. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5094. drawTriangle(data, context,
  5095. ps[i], ps[i + 1], ps[i + 2],
  5096. cs[i], cs[i + 1], cs[i + 2]);
  5097. }
  5098. break;
  5099. default:
  5100. error('illigal figure');
  5101. break;
  5102. }
  5103. }
  5104. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5105. backgroundColor) {
  5106. // we will increase scale on some weird factor to let antialiasing take
  5107. // care of "rough" edges
  5108. var EXPECTED_SCALE = 1.1;
  5109. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5110. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5111. var offsetX = Math.floor(bounds[0]);
  5112. var offsetY = Math.floor(bounds[1]);
  5113. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5114. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5115. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5116. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5117. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5118. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5119. var scaleX = boundsWidth / width;
  5120. var scaleY = boundsHeight / height;
  5121. var context = {
  5122. coords: coords,
  5123. colors: colors,
  5124. offsetX: -offsetX,
  5125. offsetY: -offsetY,
  5126. scaleX: 1 / scaleX,
  5127. scaleY: 1 / scaleY
  5128. };
  5129. var canvas, tmpCanvas, i, ii;
  5130. if (WebGLUtils.isEnabled) {
  5131. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5132. figures, context);
  5133. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5134. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5135. tmpCanvas.context.drawImage(canvas, 0, 0);
  5136. canvas = tmpCanvas.canvas;
  5137. } else {
  5138. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5139. var tmpCtx = tmpCanvas.context;
  5140. var data = tmpCtx.createImageData(width, height);
  5141. if (backgroundColor) {
  5142. var bytes = data.data;
  5143. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5144. bytes[i] = backgroundColor[0];
  5145. bytes[i + 1] = backgroundColor[1];
  5146. bytes[i + 2] = backgroundColor[2];
  5147. bytes[i + 3] = 255;
  5148. }
  5149. }
  5150. for (i = 0; i < figures.length; i++) {
  5151. drawFigure(data, figures[i], context);
  5152. }
  5153. tmpCtx.putImageData(data, 0, 0);
  5154. canvas = tmpCanvas.canvas;
  5155. }
  5156. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5157. scaleX: scaleX, scaleY: scaleY};
  5158. }
  5159. return createMeshCanvas;
  5160. })();
  5161. ShadingIRs.Mesh = {
  5162. fromIR: function Mesh_fromIR(raw) {
  5163. //var type = raw[1];
  5164. var coords = raw[2];
  5165. var colors = raw[3];
  5166. var figures = raw[4];
  5167. var bounds = raw[5];
  5168. var matrix = raw[6];
  5169. //var bbox = raw[7];
  5170. var background = raw[8];
  5171. return {
  5172. type: 'Pattern',
  5173. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5174. var scale;
  5175. if (shadingFill) {
  5176. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5177. } else {
  5178. // Obtain scale from matrix and current transformation matrix.
  5179. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5180. if (matrix) {
  5181. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5182. scale = [scale[0] * matrixScale[0],
  5183. scale[1] * matrixScale[1]];
  5184. }
  5185. }
  5186. // Rasterizing on the main thread since sending/queue large canvases
  5187. // might cause OOM.
  5188. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5189. colors, figures, shadingFill ? null : background);
  5190. if (!shadingFill) {
  5191. ctx.setTransform.apply(ctx, owner.baseTransform);
  5192. if (matrix) {
  5193. ctx.transform.apply(ctx, matrix);
  5194. }
  5195. }
  5196. ctx.translate(temporaryPatternCanvas.offsetX,
  5197. temporaryPatternCanvas.offsetY);
  5198. ctx.scale(temporaryPatternCanvas.scaleX,
  5199. temporaryPatternCanvas.scaleY);
  5200. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5201. }
  5202. };
  5203. }
  5204. };
  5205. ShadingIRs.Dummy = {
  5206. fromIR: function Dummy_fromIR() {
  5207. return {
  5208. type: 'Pattern',
  5209. getPattern: function Dummy_fromIR_getPattern() {
  5210. return 'hotpink';
  5211. }
  5212. };
  5213. }
  5214. };
  5215. function getShadingPatternFromIR(raw) {
  5216. var shadingIR = ShadingIRs[raw[0]];
  5217. if (!shadingIR) {
  5218. error('Unknown IR type: ' + raw[0]);
  5219. }
  5220. return shadingIR.fromIR(raw);
  5221. }
  5222. var TilingPattern = (function TilingPatternClosure() {
  5223. var PaintType = {
  5224. COLORED: 1,
  5225. UNCOLORED: 2
  5226. };
  5227. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5228. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5229. this.operatorList = IR[2];
  5230. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5231. this.bbox = IR[4];
  5232. this.xstep = IR[5];
  5233. this.ystep = IR[6];
  5234. this.paintType = IR[7];
  5235. this.tilingType = IR[8];
  5236. this.color = color;
  5237. this.objs = objs;
  5238. this.commonObjs = commonObjs;
  5239. this.baseTransform = baseTransform;
  5240. this.type = 'Pattern';
  5241. this.ctx = ctx;
  5242. }
  5243. TilingPattern.prototype = {
  5244. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5245. var operatorList = this.operatorList;
  5246. var bbox = this.bbox;
  5247. var xstep = this.xstep;
  5248. var ystep = this.ystep;
  5249. var paintType = this.paintType;
  5250. var tilingType = this.tilingType;
  5251. var color = this.color;
  5252. var objs = this.objs;
  5253. var commonObjs = this.commonObjs;
  5254. info('TilingType: ' + tilingType);
  5255. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5256. var topLeft = [x0, y0];
  5257. // we want the canvas to be as large as the step size
  5258. var botRight = [x0 + xstep, y0 + ystep];
  5259. var width = botRight[0] - topLeft[0];
  5260. var height = botRight[1] - topLeft[1];
  5261. // Obtain scale from matrix and current transformation matrix.
  5262. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5263. var curMatrixScale = Util.singularValueDecompose2dScale(
  5264. this.baseTransform);
  5265. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5266. matrixScale[1] * curMatrixScale[1]];
  5267. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5268. // Use width and height values that are as close as possible to the end
  5269. // result when the pattern is used. Too low value makes the pattern look
  5270. // blurry. Too large value makes it look too crispy.
  5271. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5272. MAX_PATTERN_SIZE);
  5273. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5274. MAX_PATTERN_SIZE);
  5275. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5276. var tmpCtx = tmpCanvas.context;
  5277. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5278. graphics.groupLevel = owner.groupLevel;
  5279. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5280. this.setScale(width, height, xstep, ystep);
  5281. this.transformToScale(graphics);
  5282. // transform coordinates to pattern space
  5283. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5284. graphics.transform.apply(graphics, tmpTranslate);
  5285. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5286. graphics.executeOperatorList(operatorList);
  5287. return tmpCanvas.canvas;
  5288. },
  5289. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5290. this.scale = [width / xstep, height / ystep];
  5291. },
  5292. transformToScale: function TilingPattern_transformToScale(graphics) {
  5293. var scale = this.scale;
  5294. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5295. graphics.transform.apply(graphics, tmpScale);
  5296. },
  5297. scaleToContext: function TilingPattern_scaleToContext() {
  5298. var scale = this.scale;
  5299. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5300. },
  5301. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5302. if (bbox && isArray(bbox) && bbox.length === 4) {
  5303. var bboxWidth = x1 - x0;
  5304. var bboxHeight = y1 - y0;
  5305. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5306. graphics.clip();
  5307. graphics.endPath();
  5308. }
  5309. },
  5310. setFillAndStrokeStyleToContext:
  5311. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5312. switch (paintType) {
  5313. case PaintType.COLORED:
  5314. var ctx = this.ctx;
  5315. context.fillStyle = ctx.fillStyle;
  5316. context.strokeStyle = ctx.strokeStyle;
  5317. break;
  5318. case PaintType.UNCOLORED:
  5319. var cssColor = Util.makeCssRgb(color);
  5320. context.fillStyle = cssColor;
  5321. context.strokeStyle = cssColor;
  5322. break;
  5323. default:
  5324. error('Unsupported paint type: ' + paintType);
  5325. }
  5326. },
  5327. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5328. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5329. ctx = this.ctx;
  5330. ctx.setTransform.apply(ctx, this.baseTransform);
  5331. ctx.transform.apply(ctx, this.matrix);
  5332. this.scaleToContext();
  5333. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5334. }
  5335. };
  5336. return TilingPattern;
  5337. })();
  5338. PDFJS.disableFontFace = false;
  5339. var FontLoader = {
  5340. insertRule: function fontLoaderInsertRule(rule) {
  5341. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5342. if (!styleElement) {
  5343. styleElement = document.createElement('style');
  5344. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5345. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5346. styleElement);
  5347. }
  5348. var styleSheet = styleElement.sheet;
  5349. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5350. },
  5351. clear: function fontLoaderClear() {
  5352. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5353. if (styleElement) {
  5354. styleElement.parentNode.removeChild(styleElement);
  5355. }
  5356. },
  5357. get loadTestFont() {
  5358. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5359. // height.
  5360. return shadow(this, 'loadTestFont', atob(
  5361. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5362. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5363. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5364. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5365. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5366. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5367. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5368. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5369. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5370. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5371. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5372. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5373. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5374. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5375. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5376. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5377. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5378. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5379. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5380. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5381. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5382. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5383. ));
  5384. },
  5385. loadTestFontId: 0,
  5386. loadingContext: {
  5387. requests: [],
  5388. nextRequestId: 0
  5389. },
  5390. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5391. if (isWorker) {
  5392. return false;
  5393. }
  5394. // User agent string sniffing is bad, but there is no reliable way to tell
  5395. // if font is fully loaded and ready to be used with canvas.
  5396. var userAgent = window.navigator.userAgent;
  5397. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5398. if (m && m[1] >= 14) {
  5399. return true;
  5400. }
  5401. // TODO other browsers
  5402. return false;
  5403. })(),
  5404. bind: function fontLoaderBind(fonts, callback) {
  5405. assert(!isWorker, 'bind() shall be called from main thread');
  5406. var rules = [], fontsToLoad = [];
  5407. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5408. var font = fonts[i];
  5409. // Add the font to the DOM only once or skip if the font
  5410. // is already loaded.
  5411. if (font.attached || font.loading === false) {
  5412. continue;
  5413. }
  5414. font.attached = true;
  5415. var rule = font.bindDOM();
  5416. if (rule) {
  5417. rules.push(rule);
  5418. fontsToLoad.push(font);
  5419. }
  5420. }
  5421. var request = FontLoader.queueLoadingCallback(callback);
  5422. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5423. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5424. } else {
  5425. request.complete();
  5426. }
  5427. },
  5428. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5429. function LoadLoader_completeRequest() {
  5430. assert(!request.end, 'completeRequest() cannot be called twice');
  5431. request.end = Date.now();
  5432. // sending all completed requests in order how they were queued
  5433. while (context.requests.length > 0 && context.requests[0].end) {
  5434. var otherRequest = context.requests.shift();
  5435. setTimeout(otherRequest.callback, 0);
  5436. }
  5437. }
  5438. var context = FontLoader.loadingContext;
  5439. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5440. var request = {
  5441. id: requestId,
  5442. complete: LoadLoader_completeRequest,
  5443. callback: callback,
  5444. started: Date.now()
  5445. };
  5446. context.requests.push(request);
  5447. return request;
  5448. },
  5449. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5450. fonts,
  5451. request) {
  5452. /** Hack begin */
  5453. // There's currently no event when a font has finished downloading so the
  5454. // following code is a dirty hack to 'guess' when a font is
  5455. // ready. It's assumed fonts are loaded in order, so add a known test
  5456. // font after the desired fonts and then test for the loading of that
  5457. // test font.
  5458. function int32(data, offset) {
  5459. return (data.charCodeAt(offset) << 24) |
  5460. (data.charCodeAt(offset + 1) << 16) |
  5461. (data.charCodeAt(offset + 2) << 8) |
  5462. (data.charCodeAt(offset + 3) & 0xff);
  5463. }
  5464. function spliceString(s, offset, remove, insert) {
  5465. var chunk1 = s.substr(0, offset);
  5466. var chunk2 = s.substr(offset + remove);
  5467. return chunk1 + insert + chunk2;
  5468. }
  5469. var i, ii;
  5470. var canvas = document.createElement('canvas');
  5471. canvas.width = 1;
  5472. canvas.height = 1;
  5473. var ctx = canvas.getContext('2d');
  5474. var called = 0;
  5475. function isFontReady(name, callback) {
  5476. called++;
  5477. // With setTimeout clamping this gives the font ~100ms to load.
  5478. if(called > 30) {
  5479. warn('Load test font never loaded.');
  5480. callback();
  5481. return;
  5482. }
  5483. ctx.font = '30px ' + name;
  5484. ctx.fillText('.', 0, 20);
  5485. var imageData = ctx.getImageData(0, 0, 1, 1);
  5486. if (imageData.data[3] > 0) {
  5487. callback();
  5488. return;
  5489. }
  5490. setTimeout(isFontReady.bind(null, name, callback));
  5491. }
  5492. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5493. // Chromium seems to cache fonts based on a hash of the actual font data,
  5494. // so the font must be modified for each load test else it will appear to
  5495. // be loaded already.
  5496. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5497. // font by splitting it in chunks before hand and padding the font id.
  5498. var data = this.loadTestFont;
  5499. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5500. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5501. loadTestFontId);
  5502. // CFF checksum is important for IE, adjusting it
  5503. var CFF_CHECKSUM_OFFSET = 16;
  5504. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5505. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5506. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5507. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5508. }
  5509. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5510. checksum = (checksum - XXXX_VALUE +
  5511. int32(loadTestFontId + 'XXX', i)) | 0;
  5512. }
  5513. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5514. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5515. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5516. url + '}';
  5517. FontLoader.insertRule(rule);
  5518. var names = [];
  5519. for (i = 0, ii = fonts.length; i < ii; i++) {
  5520. names.push(fonts[i].loadedName);
  5521. }
  5522. names.push(loadTestFontId);
  5523. var div = document.createElement('div');
  5524. div.setAttribute('style',
  5525. 'visibility: hidden;' +
  5526. 'width: 10px; height: 10px;' +
  5527. 'position: absolute; top: 0px; left: 0px;');
  5528. for (i = 0, ii = names.length; i < ii; ++i) {
  5529. var span = document.createElement('span');
  5530. span.textContent = 'Hi';
  5531. span.style.fontFamily = names[i];
  5532. div.appendChild(span);
  5533. }
  5534. document.body.appendChild(div);
  5535. isFontReady(loadTestFontId, function() {
  5536. document.body.removeChild(div);
  5537. request.complete();
  5538. });
  5539. /** Hack end */
  5540. }
  5541. };
  5542. var FontFace = (function FontFaceClosure() {
  5543. function FontFace(name, file, properties) {
  5544. this.compiledGlyphs = {};
  5545. if (arguments.length === 1) {
  5546. // importing translated data
  5547. var data = arguments[0];
  5548. for (var i in data) {
  5549. this[i] = data[i];
  5550. }
  5551. return;
  5552. }
  5553. }
  5554. FontFace.prototype = {
  5555. bindDOM: function FontFace_bindDOM() {
  5556. if (!this.data) {
  5557. return null;
  5558. }
  5559. if (PDFJS.disableFontFace) {
  5560. this.disableFontFace = true;
  5561. return null;
  5562. }
  5563. var data = bytesToString(new Uint8Array(this.data));
  5564. var fontName = this.loadedName;
  5565. // Add the font-face rule to the document
  5566. var url = ('url(data:' + this.mimetype + ';base64,' +
  5567. window.btoa(data) + ');');
  5568. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5569. FontLoader.insertRule(rule);
  5570. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5571. globalScope['FontInspector'].enabled) {
  5572. globalScope['FontInspector'].fontAdded(this, url);
  5573. }
  5574. return rule;
  5575. },
  5576. getPathGenerator: function (objs, character) {
  5577. if (!(character in this.compiledGlyphs)) {
  5578. var js = objs.get(this.loadedName + '_path_' + character);
  5579. /*jshint -W054 */
  5580. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5581. }
  5582. return this.compiledGlyphs[character];
  5583. }
  5584. };
  5585. return FontFace;
  5586. })();
  5587. var HIGHLIGHT_OFFSET = 4; // px
  5588. var ANNOT_MIN_SIZE = 10; // px
  5589. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5590. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5591. function setTextStyles(element, item, fontObj) {
  5592. var style = element.style;
  5593. style.fontSize = item.fontSize + 'px';
  5594. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5595. if (!fontObj) {
  5596. return;
  5597. }
  5598. style.fontWeight = fontObj.black ?
  5599. (fontObj.bold ? 'bolder' : 'bold') :
  5600. (fontObj.bold ? 'bold' : 'normal');
  5601. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5602. var fontName = fontObj.loadedName;
  5603. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5604. // Use a reasonable default font if the font doesn't specify a fallback
  5605. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5606. style.fontFamily = fontFamily + fallbackName;
  5607. }
  5608. // TODO(mack): Remove this, it's not really that helpful.
  5609. function getEmptyContainer(tagName, rect, borderWidth) {
  5610. var bWidth = borderWidth || 0;
  5611. var element = document.createElement(tagName);
  5612. element.style.borderWidth = bWidth + 'px';
  5613. var width = rect[2] - rect[0] - 2 * bWidth;
  5614. var height = rect[3] - rect[1] - 2 * bWidth;
  5615. element.style.width = width + 'px';
  5616. element.style.height = height + 'px';
  5617. return element;
  5618. }
  5619. function initContainer(item) {
  5620. var container = getEmptyContainer('section', item.rect, item.borderWidth);
  5621. container.style.backgroundColor = item.color;
  5622. var color = item.color;
  5623. var rgb = [];
  5624. for (var i = 0; i < 3; ++i) {
  5625. rgb[i] = Math.round(color[i] * 255);
  5626. }
  5627. item.colorCssRgb = Util.makeCssRgb(rgb);
  5628. var highlight = document.createElement('div');
  5629. highlight.className = 'annotationHighlight';
  5630. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  5631. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  5632. highlight.setAttribute('hidden', true);
  5633. item.highlightElement = highlight;
  5634. container.appendChild(item.highlightElement);
  5635. return container;
  5636. }
  5637. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5638. var element = getEmptyContainer('div', item.rect, 0);
  5639. element.style.display = 'table';
  5640. var content = document.createElement('div');
  5641. content.textContent = item.fieldValue;
  5642. var textAlignment = item.textAlignment;
  5643. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5644. content.style.verticalAlign = 'middle';
  5645. content.style.display = 'table-cell';
  5646. var fontObj = item.fontRefName ?
  5647. commonObjs.getData(item.fontRefName) : null;
  5648. setTextStyles(content, item, fontObj);
  5649. element.appendChild(content);
  5650. return element;
  5651. }
  5652. function getHtmlElementForTextAnnotation(item) {
  5653. var rect = item.rect;
  5654. // sanity check because of OOo-generated PDFs
  5655. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5656. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5657. }
  5658. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5659. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5660. }
  5661. var container = initContainer(item);
  5662. container.className = 'annotText';
  5663. var image = document.createElement('img');
  5664. image.style.height = container.style.height;
  5665. image.style.width = container.style.width;
  5666. var iconName = item.name;
  5667. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5668. iconName.toLowerCase() + '.svg';
  5669. image.alt = '[{{type}} Annotation]';
  5670. image.dataset.l10nId = 'text_annotation_type';
  5671. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5672. var contentWrapper = document.createElement('div');
  5673. contentWrapper.className = 'annotTextContentWrapper';
  5674. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5675. contentWrapper.style.top = '-10px';
  5676. var content = document.createElement('div');
  5677. content.className = 'annotTextContent';
  5678. content.setAttribute('hidden', true);
  5679. var i, ii;
  5680. if (item.hasBgColor) {
  5681. var color = item.color;
  5682. var rgb = [];
  5683. for (i = 0; i < 3; ++i) {
  5684. // Enlighten the color (70%)
  5685. var c = Math.round(color[i] * 255);
  5686. rgb[i] = Math.round((255 - c) * 0.7) + c;
  5687. }
  5688. content.style.backgroundColor = Util.makeCssRgb(rgb);
  5689. }
  5690. var title = document.createElement('h1');
  5691. var text = document.createElement('p');
  5692. title.textContent = item.title;
  5693. if (!item.content && !item.title) {
  5694. content.setAttribute('hidden', true);
  5695. } else {
  5696. var e = document.createElement('span');
  5697. var lines = item.content.split(/(?:\r\n?|\n)/);
  5698. for (i = 0, ii = lines.length; i < ii; ++i) {
  5699. var line = lines[i];
  5700. e.appendChild(document.createTextNode(line));
  5701. if (i < (ii - 1)) {
  5702. e.appendChild(document.createElement('br'));
  5703. }
  5704. }
  5705. text.appendChild(e);
  5706. var pinned = false;
  5707. var showAnnotation = function showAnnotation(pin) {
  5708. if (pin) {
  5709. pinned = true;
  5710. }
  5711. if (content.hasAttribute('hidden')) {
  5712. container.style.zIndex += 1;
  5713. content.removeAttribute('hidden');
  5714. }
  5715. };
  5716. var hideAnnotation = function hideAnnotation(unpin) {
  5717. if (unpin) {
  5718. pinned = false;
  5719. }
  5720. if (!content.hasAttribute('hidden') && !pinned) {
  5721. container.style.zIndex -= 1;
  5722. content.setAttribute('hidden', true);
  5723. }
  5724. };
  5725. var toggleAnnotation = function toggleAnnotation() {
  5726. if (pinned) {
  5727. hideAnnotation(true);
  5728. } else {
  5729. showAnnotation(true);
  5730. }
  5731. };
  5732. image.addEventListener('click', function image_clickHandler() {
  5733. toggleAnnotation();
  5734. }, false);
  5735. image.addEventListener('mouseover', function image_mouseOverHandler() {
  5736. showAnnotation();
  5737. }, false);
  5738. image.addEventListener('mouseout', function image_mouseOutHandler() {
  5739. hideAnnotation();
  5740. }, false);
  5741. content.addEventListener('click', function content_clickHandler() {
  5742. hideAnnotation(true);
  5743. }, false);
  5744. }
  5745. content.appendChild(title);
  5746. content.appendChild(text);
  5747. contentWrapper.appendChild(content);
  5748. container.appendChild(image);
  5749. container.appendChild(contentWrapper);
  5750. return container;
  5751. }
  5752. function getHtmlElementForLinkAnnotation(item) {
  5753. var container = initContainer(item);
  5754. container.className = 'annotLink';
  5755. container.style.borderColor = item.colorCssRgb;
  5756. container.style.borderStyle = 'solid';
  5757. var link = document.createElement('a');
  5758. link.href = link.title = item.url || '';
  5759. container.appendChild(link);
  5760. return container;
  5761. }
  5762. function getHtmlElement(data, objs) {
  5763. switch (data.annotationType) {
  5764. case AnnotationType.WIDGET:
  5765. return getHtmlElementForTextWidgetAnnotation(data, objs);
  5766. case AnnotationType.TEXT:
  5767. return getHtmlElementForTextAnnotation(data);
  5768. case AnnotationType.LINK:
  5769. return getHtmlElementForLinkAnnotation(data);
  5770. default:
  5771. throw new Error('Unsupported annotationType: ' + data.annotationType);
  5772. }
  5773. }
  5774. return {
  5775. getHtmlElement: getHtmlElement
  5776. };
  5777. })();
  5778. PDFJS.AnnotationUtils = AnnotationUtils;
  5779. }).call((typeof window === 'undefined') ? this : window);
  5780. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  5781. // workerSrc is not set -- using last script url to define default location
  5782. PDFJS.workerSrc = (function () {
  5783. 'use strict';
  5784. var scriptTagContainer = document.body ||
  5785. document.getElementsByTagName('head')[0];
  5786. var pdfjsSrc = scriptTagContainer.lastChild.src;
  5787. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  5788. })();
  5789. }