pdf.js 207 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505
  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. // Initializing PDFJS global object (if still undefined)
  19. if (typeof PDFJS === 'undefined') {
  20. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  21. }
  22. PDFJS.version = '1.0.454';
  23. PDFJS.build = 'e97efaa';
  24. (function pdfjsWrapper() {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  28. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  29. /* Copyright 2012 Mozilla Foundation
  30. *
  31. * Licensed under the Apache License, Version 2.0 (the "License");
  32. * you may not use this file except in compliance with the License.
  33. * You may obtain a copy of the License at
  34. *
  35. * http://www.apache.org/licenses/LICENSE-2.0
  36. *
  37. * Unless required by applicable law or agreed to in writing, software
  38. * distributed under the License is distributed on an "AS IS" BASIS,
  39. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. * See the License for the specific language governing permissions and
  41. * limitations under the License.
  42. */
  43. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  44. Promise */
  45. 'use strict';
  46. var globalScope = (typeof window === 'undefined') ? this : window;
  47. var isWorker = (typeof window == 'undefined');
  48. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  49. var TextRenderingMode = {
  50. FILL: 0,
  51. STROKE: 1,
  52. FILL_STROKE: 2,
  53. INVISIBLE: 3,
  54. FILL_ADD_TO_PATH: 4,
  55. STROKE_ADD_TO_PATH: 5,
  56. FILL_STROKE_ADD_TO_PATH: 6,
  57. ADD_TO_PATH: 7,
  58. FILL_STROKE_MASK: 3,
  59. ADD_TO_PATH_FLAG: 4
  60. };
  61. var ImageKind = {
  62. GRAYSCALE_1BPP: 1,
  63. RGB_24BPP: 2,
  64. RGBA_32BPP: 3
  65. };
  66. var AnnotationType = {
  67. WIDGET: 1,
  68. TEXT: 2,
  69. LINK: 3
  70. };
  71. var StreamType = {
  72. UNKNOWN: 0,
  73. FLATE: 1,
  74. LZW: 2,
  75. DCT: 3,
  76. JPX: 4,
  77. JBIG: 5,
  78. A85: 6,
  79. AHX: 7,
  80. CCF: 8,
  81. RL: 9
  82. };
  83. var FontType = {
  84. UNKNOWN: 0,
  85. TYPE1: 1,
  86. TYPE1C: 2,
  87. CIDFONTTYPE0: 3,
  88. CIDFONTTYPE0C: 4,
  89. TRUETYPE: 5,
  90. CIDFONTTYPE2: 6,
  91. TYPE3: 7,
  92. OPENTYPE: 8,
  93. TYPE0: 9,
  94. MMTYPE1: 10
  95. };
  96. // The global PDFJS object exposes the API
  97. // In production, it will be declared outside a global wrapper
  98. // In development, it will be declared here
  99. if (!globalScope.PDFJS) {
  100. globalScope.PDFJS = {};
  101. }
  102. globalScope.PDFJS.pdfBug = false;
  103. PDFJS.VERBOSITY_LEVELS = {
  104. errors: 0,
  105. warnings: 1,
  106. infos: 5
  107. };
  108. // All the possible operations for an operator list.
  109. var OPS = PDFJS.OPS = {
  110. // Intentionally start from 1 so it is easy to spot bad operators that will be
  111. // 0's.
  112. dependency: 1,
  113. setLineWidth: 2,
  114. setLineCap: 3,
  115. setLineJoin: 4,
  116. setMiterLimit: 5,
  117. setDash: 6,
  118. setRenderingIntent: 7,
  119. setFlatness: 8,
  120. setGState: 9,
  121. save: 10,
  122. restore: 11,
  123. transform: 12,
  124. moveTo: 13,
  125. lineTo: 14,
  126. curveTo: 15,
  127. curveTo2: 16,
  128. curveTo3: 17,
  129. closePath: 18,
  130. rectangle: 19,
  131. stroke: 20,
  132. closeStroke: 21,
  133. fill: 22,
  134. eoFill: 23,
  135. fillStroke: 24,
  136. eoFillStroke: 25,
  137. closeFillStroke: 26,
  138. closeEOFillStroke: 27,
  139. endPath: 28,
  140. clip: 29,
  141. eoClip: 30,
  142. beginText: 31,
  143. endText: 32,
  144. setCharSpacing: 33,
  145. setWordSpacing: 34,
  146. setHScale: 35,
  147. setLeading: 36,
  148. setFont: 37,
  149. setTextRenderingMode: 38,
  150. setTextRise: 39,
  151. moveText: 40,
  152. setLeadingMoveText: 41,
  153. setTextMatrix: 42,
  154. nextLine: 43,
  155. showText: 44,
  156. showSpacedText: 45,
  157. nextLineShowText: 46,
  158. nextLineSetSpacingShowText: 47,
  159. setCharWidth: 48,
  160. setCharWidthAndBounds: 49,
  161. setStrokeColorSpace: 50,
  162. setFillColorSpace: 51,
  163. setStrokeColor: 52,
  164. setStrokeColorN: 53,
  165. setFillColor: 54,
  166. setFillColorN: 55,
  167. setStrokeGray: 56,
  168. setFillGray: 57,
  169. setStrokeRGBColor: 58,
  170. setFillRGBColor: 59,
  171. setStrokeCMYKColor: 60,
  172. setFillCMYKColor: 61,
  173. shadingFill: 62,
  174. beginInlineImage: 63,
  175. beginImageData: 64,
  176. endInlineImage: 65,
  177. paintXObject: 66,
  178. markPoint: 67,
  179. markPointProps: 68,
  180. beginMarkedContent: 69,
  181. beginMarkedContentProps: 70,
  182. endMarkedContent: 71,
  183. beginCompat: 72,
  184. endCompat: 73,
  185. paintFormXObjectBegin: 74,
  186. paintFormXObjectEnd: 75,
  187. beginGroup: 76,
  188. endGroup: 77,
  189. beginAnnotations: 78,
  190. endAnnotations: 79,
  191. beginAnnotation: 80,
  192. endAnnotation: 81,
  193. paintJpegXObject: 82,
  194. paintImageMaskXObject: 83,
  195. paintImageMaskXObjectGroup: 84,
  196. paintImageXObject: 85,
  197. paintInlineImageXObject: 86,
  198. paintInlineImageXObjectGroup: 87,
  199. paintImageXObjectRepeat: 88,
  200. paintImageMaskXObjectRepeat: 89,
  201. paintSolidColorImageMask: 90,
  202. constructPath: 91
  203. };
  204. // A notice for devs. These are good for things that are helpful to devs, such
  205. // as warning that Workers were disabled, which is important to devs but not
  206. // end users.
  207. function info(msg) {
  208. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  209. console.log('Info: ' + msg);
  210. }
  211. }
  212. // Non-fatal warnings.
  213. function warn(msg) {
  214. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  215. console.log('Warning: ' + msg);
  216. }
  217. }
  218. // Fatal errors that should trigger the fallback UI and halt execution by
  219. // throwing an exception.
  220. function error(msg) {
  221. // If multiple arguments were passed, pass them all to the log function.
  222. if (arguments.length > 1) {
  223. var logArguments = ['Error:'];
  224. logArguments.push.apply(logArguments, arguments);
  225. console.log.apply(console, logArguments);
  226. // Join the arguments into a single string for the lines below.
  227. msg = [].join.call(arguments, ' ');
  228. } else {
  229. console.log('Error: ' + msg);
  230. }
  231. console.log(backtrace());
  232. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  233. throw new Error(msg);
  234. }
  235. function backtrace() {
  236. try {
  237. throw new Error();
  238. } catch (e) {
  239. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  240. }
  241. }
  242. function assert(cond, msg) {
  243. if (!cond) {
  244. error(msg);
  245. }
  246. }
  247. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  248. unknown: 'unknown',
  249. forms: 'forms',
  250. javaScript: 'javaScript',
  251. smask: 'smask',
  252. shadingPattern: 'shadingPattern',
  253. font: 'font'
  254. };
  255. var UnsupportedManager = PDFJS.UnsupportedManager =
  256. (function UnsupportedManagerClosure() {
  257. var listeners = [];
  258. return {
  259. listen: function (cb) {
  260. listeners.push(cb);
  261. },
  262. notify: function (featureId) {
  263. warn('Unsupported feature "' + featureId + '"');
  264. for (var i = 0, ii = listeners.length; i < ii; i++) {
  265. listeners[i](featureId);
  266. }
  267. }
  268. };
  269. })();
  270. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  271. // absolute URL, it will be returned as is.
  272. function combineUrl(baseUrl, url) {
  273. if (!url) {
  274. return baseUrl;
  275. }
  276. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  277. return url;
  278. }
  279. var i;
  280. if (url.charAt(0) == '/') {
  281. // absolute path
  282. i = baseUrl.indexOf('://');
  283. if (url.charAt(1) === '/') {
  284. ++i;
  285. } else {
  286. i = baseUrl.indexOf('/', i + 3);
  287. }
  288. return baseUrl.substring(0, i) + url;
  289. } else {
  290. // relative path
  291. var pathLength = baseUrl.length;
  292. i = baseUrl.lastIndexOf('#');
  293. pathLength = i >= 0 ? i : pathLength;
  294. i = baseUrl.lastIndexOf('?', pathLength);
  295. pathLength = i >= 0 ? i : pathLength;
  296. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  297. return baseUrl.substring(0, prefixLength + 1) + url;
  298. }
  299. }
  300. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  301. function isValidUrl(url, allowRelative) {
  302. if (!url) {
  303. return false;
  304. }
  305. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  306. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  307. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  308. if (!protocol) {
  309. return allowRelative;
  310. }
  311. protocol = protocol[0].toLowerCase();
  312. switch (protocol) {
  313. case 'http':
  314. case 'https':
  315. case 'ftp':
  316. case 'mailto':
  317. return true;
  318. default:
  319. return false;
  320. }
  321. }
  322. PDFJS.isValidUrl = isValidUrl;
  323. function shadow(obj, prop, value) {
  324. Object.defineProperty(obj, prop, { value: value,
  325. enumerable: true,
  326. configurable: true,
  327. writable: false });
  328. return value;
  329. }
  330. var PasswordResponses = PDFJS.PasswordResponses = {
  331. NEED_PASSWORD: 1,
  332. INCORRECT_PASSWORD: 2
  333. };
  334. var PasswordException = (function PasswordExceptionClosure() {
  335. function PasswordException(msg, code) {
  336. this.name = 'PasswordException';
  337. this.message = msg;
  338. this.code = code;
  339. }
  340. PasswordException.prototype = new Error();
  341. PasswordException.constructor = PasswordException;
  342. return PasswordException;
  343. })();
  344. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  345. function UnknownErrorException(msg, details) {
  346. this.name = 'UnknownErrorException';
  347. this.message = msg;
  348. this.details = details;
  349. }
  350. UnknownErrorException.prototype = new Error();
  351. UnknownErrorException.constructor = UnknownErrorException;
  352. return UnknownErrorException;
  353. })();
  354. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  355. function InvalidPDFException(msg) {
  356. this.name = 'InvalidPDFException';
  357. this.message = msg;
  358. }
  359. InvalidPDFException.prototype = new Error();
  360. InvalidPDFException.constructor = InvalidPDFException;
  361. return InvalidPDFException;
  362. })();
  363. var MissingPDFException = (function MissingPDFExceptionClosure() {
  364. function MissingPDFException(msg) {
  365. this.name = 'MissingPDFException';
  366. this.message = msg;
  367. }
  368. MissingPDFException.prototype = new Error();
  369. MissingPDFException.constructor = MissingPDFException;
  370. return MissingPDFException;
  371. })();
  372. var NotImplementedException = (function NotImplementedExceptionClosure() {
  373. function NotImplementedException(msg) {
  374. this.message = msg;
  375. }
  376. NotImplementedException.prototype = new Error();
  377. NotImplementedException.prototype.name = 'NotImplementedException';
  378. NotImplementedException.constructor = NotImplementedException;
  379. return NotImplementedException;
  380. })();
  381. var MissingDataException = (function MissingDataExceptionClosure() {
  382. function MissingDataException(begin, end) {
  383. this.begin = begin;
  384. this.end = end;
  385. this.message = 'Missing data [' + begin + ', ' + end + ')';
  386. }
  387. MissingDataException.prototype = new Error();
  388. MissingDataException.prototype.name = 'MissingDataException';
  389. MissingDataException.constructor = MissingDataException;
  390. return MissingDataException;
  391. })();
  392. var XRefParseException = (function XRefParseExceptionClosure() {
  393. function XRefParseException(msg) {
  394. this.message = msg;
  395. }
  396. XRefParseException.prototype = new Error();
  397. XRefParseException.prototype.name = 'XRefParseException';
  398. XRefParseException.constructor = XRefParseException;
  399. return XRefParseException;
  400. })();
  401. function bytesToString(bytes) {
  402. var length = bytes.length;
  403. var MAX_ARGUMENT_COUNT = 8192;
  404. if (length < MAX_ARGUMENT_COUNT) {
  405. return String.fromCharCode.apply(null, bytes);
  406. }
  407. var strBuf = [];
  408. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  409. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  410. var chunk = bytes.subarray(i, chunkEnd);
  411. strBuf.push(String.fromCharCode.apply(null, chunk));
  412. }
  413. return strBuf.join('');
  414. }
  415. function stringToArray(str) {
  416. var length = str.length;
  417. var array = [];
  418. for (var i = 0; i < length; ++i) {
  419. array[i] = str.charCodeAt(i);
  420. }
  421. return array;
  422. }
  423. function stringToBytes(str) {
  424. var length = str.length;
  425. var bytes = new Uint8Array(length);
  426. for (var i = 0; i < length; ++i) {
  427. bytes[i] = str.charCodeAt(i) & 0xFF;
  428. }
  429. return bytes;
  430. }
  431. function string32(value) {
  432. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  433. (value >> 8) & 0xff, value & 0xff);
  434. }
  435. function log2(x) {
  436. var n = 1, i = 0;
  437. while (x > n) {
  438. n <<= 1;
  439. i++;
  440. }
  441. return i;
  442. }
  443. function readInt8(data, start) {
  444. return (data[start] << 24) >> 24;
  445. }
  446. function readUint16(data, offset) {
  447. return (data[offset] << 8) | data[offset + 1];
  448. }
  449. function readUint32(data, offset) {
  450. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  451. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  452. }
  453. // Lazy test the endianness of the platform
  454. // NOTE: This will be 'true' for simulated TypedArrays
  455. function isLittleEndian() {
  456. var buffer8 = new Uint8Array(2);
  457. buffer8[0] = 1;
  458. var buffer16 = new Uint16Array(buffer8.buffer);
  459. return (buffer16[0] === 1);
  460. }
  461. Object.defineProperty(PDFJS, 'isLittleEndian', {
  462. configurable: true,
  463. get: function PDFJS_isLittleEndian() {
  464. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  465. }
  466. });
  467. // Lazy test if the userAgant support CanvasTypedArrays
  468. function hasCanvasTypedArrays() {
  469. var canvas = document.createElement('canvas');
  470. canvas.width = canvas.height = 1;
  471. var ctx = canvas.getContext('2d');
  472. var imageData = ctx.createImageData(1, 1);
  473. return (typeof imageData.data.buffer !== 'undefined');
  474. }
  475. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  476. configurable: true,
  477. get: function PDFJS_hasCanvasTypedArrays() {
  478. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  479. }
  480. });
  481. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  482. function Uint32ArrayView(buffer, length) {
  483. this.buffer = buffer;
  484. this.byteLength = buffer.length;
  485. this.length = length === undefined ? (this.byteLength >> 2) : length;
  486. ensureUint32ArrayViewProps(this.length);
  487. }
  488. Uint32ArrayView.prototype = Object.create(null);
  489. var uint32ArrayViewSetters = 0;
  490. function createUint32ArrayProp(index) {
  491. return {
  492. get: function () {
  493. var buffer = this.buffer, offset = index << 2;
  494. return (buffer[offset] | (buffer[offset + 1] << 8) |
  495. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  496. },
  497. set: function (value) {
  498. var buffer = this.buffer, offset = index << 2;
  499. buffer[offset] = value & 255;
  500. buffer[offset + 1] = (value >> 8) & 255;
  501. buffer[offset + 2] = (value >> 16) & 255;
  502. buffer[offset + 3] = (value >>> 24) & 255;
  503. }
  504. };
  505. }
  506. function ensureUint32ArrayViewProps(length) {
  507. while (uint32ArrayViewSetters < length) {
  508. Object.defineProperty(Uint32ArrayView.prototype,
  509. uint32ArrayViewSetters,
  510. createUint32ArrayProp(uint32ArrayViewSetters));
  511. uint32ArrayViewSetters++;
  512. }
  513. }
  514. return Uint32ArrayView;
  515. })();
  516. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  517. var Util = PDFJS.Util = (function UtilClosure() {
  518. function Util() {}
  519. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  520. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  521. // creating many intermediate strings.
  522. Util.makeCssRgb = function Util_makeCssRgb(rgb) {
  523. rgbBuf[1] = rgb[0];
  524. rgbBuf[3] = rgb[1];
  525. rgbBuf[5] = rgb[2];
  526. return rgbBuf.join('');
  527. };
  528. // Concatenates two transformation matrices together and returns the result.
  529. Util.transform = function Util_transform(m1, m2) {
  530. return [
  531. m1[0] * m2[0] + m1[2] * m2[1],
  532. m1[1] * m2[0] + m1[3] * m2[1],
  533. m1[0] * m2[2] + m1[2] * m2[3],
  534. m1[1] * m2[2] + m1[3] * m2[3],
  535. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  536. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  537. ];
  538. };
  539. // For 2d affine transforms
  540. Util.applyTransform = function Util_applyTransform(p, m) {
  541. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  542. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  543. return [xt, yt];
  544. };
  545. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  546. var d = m[0] * m[3] - m[1] * m[2];
  547. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  548. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  549. return [xt, yt];
  550. };
  551. // Applies the transform to the rectangle and finds the minimum axially
  552. // aligned bounding box.
  553. Util.getAxialAlignedBoundingBox =
  554. function Util_getAxialAlignedBoundingBox(r, m) {
  555. var p1 = Util.applyTransform(r, m);
  556. var p2 = Util.applyTransform(r.slice(2, 4), m);
  557. var p3 = Util.applyTransform([r[0], r[3]], m);
  558. var p4 = Util.applyTransform([r[2], r[1]], m);
  559. return [
  560. Math.min(p1[0], p2[0], p3[0], p4[0]),
  561. Math.min(p1[1], p2[1], p3[1], p4[1]),
  562. Math.max(p1[0], p2[0], p3[0], p4[0]),
  563. Math.max(p1[1], p2[1], p3[1], p4[1])
  564. ];
  565. };
  566. Util.inverseTransform = function Util_inverseTransform(m) {
  567. var d = m[0] * m[3] - m[1] * m[2];
  568. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  569. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  570. };
  571. // Apply a generic 3d matrix M on a 3-vector v:
  572. // | a b c | | X |
  573. // | d e f | x | Y |
  574. // | g h i | | Z |
  575. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  576. // with v as [X,Y,Z]
  577. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  578. return [
  579. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  580. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  581. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  582. ];
  583. };
  584. // This calculation uses Singular Value Decomposition.
  585. // The SVD can be represented with formula A = USV. We are interested in the
  586. // matrix S here because it represents the scale values.
  587. Util.singularValueDecompose2dScale =
  588. function Util_singularValueDecompose2dScale(m) {
  589. var transpose = [m[0], m[2], m[1], m[3]];
  590. // Multiply matrix m with its transpose.
  591. var a = m[0] * transpose[0] + m[1] * transpose[2];
  592. var b = m[0] * transpose[1] + m[1] * transpose[3];
  593. var c = m[2] * transpose[0] + m[3] * transpose[2];
  594. var d = m[2] * transpose[1] + m[3] * transpose[3];
  595. // Solve the second degree polynomial to get roots.
  596. var first = (a + d) / 2;
  597. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  598. var sx = first + second || 1;
  599. var sy = first - second || 1;
  600. // Scale values are the square roots of the eigenvalues.
  601. return [Math.sqrt(sx), Math.sqrt(sy)];
  602. };
  603. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  604. // For coordinate systems whose origin lies in the bottom-left, this
  605. // means normalization to (BL,TR) ordering. For systems with origin in the
  606. // top-left, this means (TL,BR) ordering.
  607. Util.normalizeRect = function Util_normalizeRect(rect) {
  608. var r = rect.slice(0); // clone rect
  609. if (rect[0] > rect[2]) {
  610. r[0] = rect[2];
  611. r[2] = rect[0];
  612. }
  613. if (rect[1] > rect[3]) {
  614. r[1] = rect[3];
  615. r[3] = rect[1];
  616. }
  617. return r;
  618. };
  619. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  620. // intersection of rect1 and rect2. If no intersection, returns 'false'
  621. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  622. Util.intersect = function Util_intersect(rect1, rect2) {
  623. function compare(a, b) {
  624. return a - b;
  625. }
  626. // Order points along the axes
  627. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  628. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  629. result = [];
  630. rect1 = Util.normalizeRect(rect1);
  631. rect2 = Util.normalizeRect(rect2);
  632. // X: first and second points belong to different rectangles?
  633. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  634. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  635. // Intersection must be between second and third points
  636. result[0] = orderedX[1];
  637. result[2] = orderedX[2];
  638. } else {
  639. return false;
  640. }
  641. // Y: first and second points belong to different rectangles?
  642. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  643. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  644. // Intersection must be between second and third points
  645. result[1] = orderedY[1];
  646. result[3] = orderedY[2];
  647. } else {
  648. return false;
  649. }
  650. return result;
  651. };
  652. Util.sign = function Util_sign(num) {
  653. return num < 0 ? -1 : 1;
  654. };
  655. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  656. Array.prototype.push.apply(arr1, arr2);
  657. };
  658. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  659. Array.prototype.unshift.apply(arr1, arr2);
  660. };
  661. Util.extendObj = function extendObj(obj1, obj2) {
  662. for (var key in obj2) {
  663. obj1[key] = obj2[key];
  664. }
  665. };
  666. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  667. name) {
  668. while (dict && !dict.has(name)) {
  669. dict = dict.get('Parent');
  670. }
  671. if (!dict) {
  672. return null;
  673. }
  674. return dict.get(name);
  675. };
  676. Util.inherit = function Util_inherit(sub, base, prototype) {
  677. sub.prototype = Object.create(base.prototype);
  678. sub.prototype.constructor = sub;
  679. for (var prop in prototype) {
  680. sub.prototype[prop] = prototype[prop];
  681. }
  682. };
  683. Util.loadScript = function Util_loadScript(src, callback) {
  684. var script = document.createElement('script');
  685. var loaded = false;
  686. script.setAttribute('src', src);
  687. if (callback) {
  688. script.onload = function() {
  689. if (!loaded) {
  690. callback();
  691. }
  692. loaded = true;
  693. };
  694. }
  695. document.getElementsByTagName('head')[0].appendChild(script);
  696. };
  697. return Util;
  698. })();
  699. /**
  700. * PDF page viewport created based on scale, rotation and offset.
  701. * @class
  702. * @alias PDFJS.PageViewport
  703. */
  704. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  705. /**
  706. * @constructor
  707. * @private
  708. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  709. * @param scale {number} scale of the viewport.
  710. * @param rotation {number} rotations of the viewport in degrees.
  711. * @param offsetX {number} offset X
  712. * @param offsetY {number} offset Y
  713. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  714. */
  715. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  716. this.viewBox = viewBox;
  717. this.scale = scale;
  718. this.rotation = rotation;
  719. this.offsetX = offsetX;
  720. this.offsetY = offsetY;
  721. // creating transform to convert pdf coordinate system to the normal
  722. // canvas like coordinates taking in account scale and rotation
  723. var centerX = (viewBox[2] + viewBox[0]) / 2;
  724. var centerY = (viewBox[3] + viewBox[1]) / 2;
  725. var rotateA, rotateB, rotateC, rotateD;
  726. rotation = rotation % 360;
  727. rotation = rotation < 0 ? rotation + 360 : rotation;
  728. switch (rotation) {
  729. case 180:
  730. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  731. break;
  732. case 90:
  733. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  734. break;
  735. case 270:
  736. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  737. break;
  738. //case 0:
  739. default:
  740. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  741. break;
  742. }
  743. if (dontFlip) {
  744. rotateC = -rotateC; rotateD = -rotateD;
  745. }
  746. var offsetCanvasX, offsetCanvasY;
  747. var width, height;
  748. if (rotateA === 0) {
  749. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  750. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  751. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  752. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  753. } else {
  754. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  755. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  756. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  757. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  758. }
  759. // creating transform for the following operations:
  760. // translate(-centerX, -centerY), rotate and flip vertically,
  761. // scale, and translate(offsetCanvasX, offsetCanvasY)
  762. this.transform = [
  763. rotateA * scale,
  764. rotateB * scale,
  765. rotateC * scale,
  766. rotateD * scale,
  767. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  768. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  769. ];
  770. this.width = width;
  771. this.height = height;
  772. this.fontScale = scale;
  773. }
  774. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  775. /**
  776. * Clones viewport with additional properties.
  777. * @param args {Object} (optional) If specified, may contain the 'scale' or
  778. * 'rotation' properties to override the corresponding properties in
  779. * the cloned viewport.
  780. * @returns {PDFJS.PageViewport} Cloned viewport.
  781. */
  782. clone: function PageViewPort_clone(args) {
  783. args = args || {};
  784. var scale = 'scale' in args ? args.scale : this.scale;
  785. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  786. return new PageViewport(this.viewBox.slice(), scale, rotation,
  787. this.offsetX, this.offsetY, args.dontFlip);
  788. },
  789. /**
  790. * Converts PDF point to the viewport coordinates. For examples, useful for
  791. * converting PDF location into canvas pixel coordinates.
  792. * @param x {number} X coordinate.
  793. * @param y {number} Y coordinate.
  794. * @returns {Object} Object that contains 'x' and 'y' properties of the
  795. * point in the viewport coordinate space.
  796. * @see {@link convertToPdfPoint}
  797. * @see {@link convertToViewportRectangle}
  798. */
  799. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  800. return Util.applyTransform([x, y], this.transform);
  801. },
  802. /**
  803. * Converts PDF rectangle to the viewport coordinates.
  804. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  805. * @returns {Array} Contains corresponding coordinates of the rectangle
  806. * in the viewport coordinate space.
  807. * @see {@link convertToViewportPoint}
  808. */
  809. convertToViewportRectangle:
  810. function PageViewport_convertToViewportRectangle(rect) {
  811. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  812. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  813. return [tl[0], tl[1], br[0], br[1]];
  814. },
  815. /**
  816. * Converts viewport coordinates to the PDF location. For examples, useful
  817. * for converting canvas pixel location into PDF one.
  818. * @param x {number} X coordinate.
  819. * @param y {number} Y coordinate.
  820. * @returns {Object} Object that contains 'x' and 'y' properties of the
  821. * point in the PDF coordinate space.
  822. * @see {@link convertToViewportPoint}
  823. */
  824. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  825. return Util.applyInverseTransform([x, y], this.transform);
  826. }
  827. };
  828. return PageViewport;
  829. })();
  830. var PDFStringTranslateTable = [
  831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  832. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  833. 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,
  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, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  837. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  838. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  839. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  840. ];
  841. function stringToPDFString(str) {
  842. var i, n = str.length, strBuf = [];
  843. if (str[0] === '\xFE' && str[1] === '\xFF') {
  844. // UTF16BE BOM
  845. for (i = 2; i < n; i += 2) {
  846. strBuf.push(String.fromCharCode(
  847. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  848. }
  849. } else {
  850. for (i = 0; i < n; ++i) {
  851. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  852. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  853. }
  854. }
  855. return strBuf.join('');
  856. }
  857. function stringToUTF8String(str) {
  858. return decodeURIComponent(escape(str));
  859. }
  860. function isEmptyObj(obj) {
  861. for (var key in obj) {
  862. return false;
  863. }
  864. return true;
  865. }
  866. function isBool(v) {
  867. return typeof v == 'boolean';
  868. }
  869. function isInt(v) {
  870. return typeof v === 'number' && ((v | 0) === v);
  871. }
  872. function isNum(v) {
  873. return typeof v === 'number';
  874. }
  875. function isString(v) {
  876. return typeof v === 'string';
  877. }
  878. function isNull(v) {
  879. return v === null;
  880. }
  881. function isName(v) {
  882. return v instanceof Name;
  883. }
  884. function isCmd(v, cmd) {
  885. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  886. }
  887. function isDict(v, type) {
  888. if (!(v instanceof Dict)) {
  889. return false;
  890. }
  891. if (!type) {
  892. return true;
  893. }
  894. var dictType = v.get('Type');
  895. return isName(dictType) && dictType.name === type;
  896. }
  897. function isArray(v) {
  898. return v instanceof Array;
  899. }
  900. function isStream(v) {
  901. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  902. }
  903. function isArrayBuffer(v) {
  904. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  905. }
  906. function isRef(v) {
  907. return v instanceof Ref;
  908. }
  909. /**
  910. * Promise Capability object.
  911. *
  912. * @typedef {Object} PromiseCapability
  913. * @property {Promise} promise - A promise object.
  914. * @property {function} resolve - Fullfills the promise.
  915. * @property {function} reject - Rejects the promise.
  916. */
  917. /**
  918. * Creates a promise capability object.
  919. * @alias PDFJS.createPromiseCapability
  920. *
  921. * @return {PromiseCapability} A capability object contains:
  922. * - a Promise, resolve and reject methods.
  923. */
  924. function createPromiseCapability() {
  925. var capability = {};
  926. capability.promise = new Promise(function (resolve, reject) {
  927. capability.resolve = resolve;
  928. capability.reject = reject;
  929. });
  930. return capability;
  931. }
  932. PDFJS.createPromiseCapability = createPromiseCapability;
  933. /**
  934. * Polyfill for Promises:
  935. * The following promise implementation tries to generally implement the
  936. * Promise/A+ spec. Some notable differences from other promise libaries are:
  937. * - There currently isn't a seperate deferred and promise object.
  938. * - Unhandled rejections eventually show an error if they aren't handled.
  939. *
  940. * Based off of the work in:
  941. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  942. */
  943. (function PromiseClosure() {
  944. if (globalScope.Promise) {
  945. // Promises existing in the DOM/Worker, checking presence of all/resolve
  946. if (typeof globalScope.Promise.all !== 'function') {
  947. globalScope.Promise.all = function (iterable) {
  948. var count = 0, results = [], resolve, reject;
  949. var promise = new globalScope.Promise(function (resolve_, reject_) {
  950. resolve = resolve_;
  951. reject = reject_;
  952. });
  953. iterable.forEach(function (p, i) {
  954. count++;
  955. p.then(function (result) {
  956. results[i] = result;
  957. count--;
  958. if (count === 0) {
  959. resolve(results);
  960. }
  961. }, reject);
  962. });
  963. if (count === 0) {
  964. resolve(results);
  965. }
  966. return promise;
  967. };
  968. }
  969. if (typeof globalScope.Promise.resolve !== 'function') {
  970. globalScope.Promise.resolve = function (value) {
  971. return new globalScope.Promise(function (resolve) { resolve(value); });
  972. };
  973. }
  974. if (typeof globalScope.Promise.reject !== 'function') {
  975. globalScope.Promise.reject = function (reason) {
  976. return new globalScope.Promise(function (resolve, reject) {
  977. reject(reason);
  978. });
  979. };
  980. }
  981. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  982. globalScope.Promise.prototype.catch = function (onReject) {
  983. return globalScope.Promise.prototype.then(undefined, onReject);
  984. };
  985. }
  986. return;
  987. }
  988. var STATUS_PENDING = 0;
  989. var STATUS_RESOLVED = 1;
  990. var STATUS_REJECTED = 2;
  991. // In an attempt to avoid silent exceptions, unhandled rejections are
  992. // tracked and if they aren't handled in a certain amount of time an
  993. // error is logged.
  994. var REJECTION_TIMEOUT = 500;
  995. var HandlerManager = {
  996. handlers: [],
  997. running: false,
  998. unhandledRejections: [],
  999. pendingRejectionCheck: false,
  1000. scheduleHandlers: function scheduleHandlers(promise) {
  1001. if (promise._status == STATUS_PENDING) {
  1002. return;
  1003. }
  1004. this.handlers = this.handlers.concat(promise._handlers);
  1005. promise._handlers = [];
  1006. if (this.running) {
  1007. return;
  1008. }
  1009. this.running = true;
  1010. setTimeout(this.runHandlers.bind(this), 0);
  1011. },
  1012. runHandlers: function runHandlers() {
  1013. var RUN_TIMEOUT = 1; // ms
  1014. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1015. while (this.handlers.length > 0) {
  1016. var handler = this.handlers.shift();
  1017. var nextStatus = handler.thisPromise._status;
  1018. var nextValue = handler.thisPromise._value;
  1019. try {
  1020. if (nextStatus === STATUS_RESOLVED) {
  1021. if (typeof(handler.onResolve) == 'function') {
  1022. nextValue = handler.onResolve(nextValue);
  1023. }
  1024. } else if (typeof(handler.onReject) === 'function') {
  1025. nextValue = handler.onReject(nextValue);
  1026. nextStatus = STATUS_RESOLVED;
  1027. if (handler.thisPromise._unhandledRejection) {
  1028. this.removeUnhandeledRejection(handler.thisPromise);
  1029. }
  1030. }
  1031. } catch (ex) {
  1032. nextStatus = STATUS_REJECTED;
  1033. nextValue = ex;
  1034. }
  1035. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1036. if (Date.now() >= timeoutAt) {
  1037. break;
  1038. }
  1039. }
  1040. if (this.handlers.length > 0) {
  1041. setTimeout(this.runHandlers.bind(this), 0);
  1042. return;
  1043. }
  1044. this.running = false;
  1045. },
  1046. addUnhandledRejection: function addUnhandledRejection(promise) {
  1047. this.unhandledRejections.push({
  1048. promise: promise,
  1049. time: Date.now()
  1050. });
  1051. this.scheduleRejectionCheck();
  1052. },
  1053. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1054. promise._unhandledRejection = false;
  1055. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1056. if (this.unhandledRejections[i].promise === promise) {
  1057. this.unhandledRejections.splice(i);
  1058. i--;
  1059. }
  1060. }
  1061. },
  1062. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1063. if (this.pendingRejectionCheck) {
  1064. return;
  1065. }
  1066. this.pendingRejectionCheck = true;
  1067. setTimeout(function rejectionCheck() {
  1068. this.pendingRejectionCheck = false;
  1069. var now = Date.now();
  1070. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1071. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1072. var unhandled = this.unhandledRejections[i].promise._value;
  1073. var msg = 'Unhandled rejection: ' + unhandled;
  1074. if (unhandled.stack) {
  1075. msg += '\n' + unhandled.stack;
  1076. }
  1077. warn(msg);
  1078. this.unhandledRejections.splice(i);
  1079. i--;
  1080. }
  1081. }
  1082. if (this.unhandledRejections.length) {
  1083. this.scheduleRejectionCheck();
  1084. }
  1085. }.bind(this), REJECTION_TIMEOUT);
  1086. }
  1087. };
  1088. function Promise(resolver) {
  1089. this._status = STATUS_PENDING;
  1090. this._handlers = [];
  1091. try {
  1092. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1093. } catch (e) {
  1094. this._reject(e);
  1095. }
  1096. }
  1097. /**
  1098. * Builds a promise that is resolved when all the passed in promises are
  1099. * resolved.
  1100. * @param {array} array of data and/or promises to wait for.
  1101. * @return {Promise} New dependant promise.
  1102. */
  1103. Promise.all = function Promise_all(promises) {
  1104. var resolveAll, rejectAll;
  1105. var deferred = new Promise(function (resolve, reject) {
  1106. resolveAll = resolve;
  1107. rejectAll = reject;
  1108. });
  1109. var unresolved = promises.length;
  1110. var results = [];
  1111. if (unresolved === 0) {
  1112. resolveAll(results);
  1113. return deferred;
  1114. }
  1115. function reject(reason) {
  1116. if (deferred._status === STATUS_REJECTED) {
  1117. return;
  1118. }
  1119. results = [];
  1120. rejectAll(reason);
  1121. }
  1122. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1123. var promise = promises[i];
  1124. var resolve = (function(i) {
  1125. return function(value) {
  1126. if (deferred._status === STATUS_REJECTED) {
  1127. return;
  1128. }
  1129. results[i] = value;
  1130. unresolved--;
  1131. if (unresolved === 0) {
  1132. resolveAll(results);
  1133. }
  1134. };
  1135. })(i);
  1136. if (Promise.isPromise(promise)) {
  1137. promise.then(resolve, reject);
  1138. } else {
  1139. resolve(promise);
  1140. }
  1141. }
  1142. return deferred;
  1143. };
  1144. /**
  1145. * Checks if the value is likely a promise (has a 'then' function).
  1146. * @return {boolean} true if value is thenable
  1147. */
  1148. Promise.isPromise = function Promise_isPromise(value) {
  1149. return value && typeof value.then === 'function';
  1150. };
  1151. /**
  1152. * Creates resolved promise
  1153. * @param value resolve value
  1154. * @returns {Promise}
  1155. */
  1156. Promise.resolve = function Promise_resolve(value) {
  1157. return new Promise(function (resolve) { resolve(value); });
  1158. };
  1159. /**
  1160. * Creates rejected promise
  1161. * @param reason rejection value
  1162. * @returns {Promise}
  1163. */
  1164. Promise.reject = function Promise_reject(reason) {
  1165. return new Promise(function (resolve, reject) { reject(reason); });
  1166. };
  1167. Promise.prototype = {
  1168. _status: null,
  1169. _value: null,
  1170. _handlers: null,
  1171. _unhandledRejection: null,
  1172. _updateStatus: function Promise__updateStatus(status, value) {
  1173. if (this._status === STATUS_RESOLVED ||
  1174. this._status === STATUS_REJECTED) {
  1175. return;
  1176. }
  1177. if (status == STATUS_RESOLVED &&
  1178. Promise.isPromise(value)) {
  1179. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1180. this._updateStatus.bind(this, STATUS_REJECTED));
  1181. return;
  1182. }
  1183. this._status = status;
  1184. this._value = value;
  1185. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1186. this._unhandledRejection = true;
  1187. HandlerManager.addUnhandledRejection(this);
  1188. }
  1189. HandlerManager.scheduleHandlers(this);
  1190. },
  1191. _resolve: function Promise_resolve(value) {
  1192. this._updateStatus(STATUS_RESOLVED, value);
  1193. },
  1194. _reject: function Promise_reject(reason) {
  1195. this._updateStatus(STATUS_REJECTED, reason);
  1196. },
  1197. then: function Promise_then(onResolve, onReject) {
  1198. var nextPromise = new Promise(function (resolve, reject) {
  1199. this.resolve = reject;
  1200. this.reject = reject;
  1201. });
  1202. this._handlers.push({
  1203. thisPromise: this,
  1204. onResolve: onResolve,
  1205. onReject: onReject,
  1206. nextPromise: nextPromise
  1207. });
  1208. HandlerManager.scheduleHandlers(this);
  1209. return nextPromise;
  1210. },
  1211. catch: function Promise_catch(onReject) {
  1212. return this.then(undefined, onReject);
  1213. }
  1214. };
  1215. globalScope.Promise = Promise;
  1216. })();
  1217. var StatTimer = (function StatTimerClosure() {
  1218. function rpad(str, pad, length) {
  1219. while (str.length < length) {
  1220. str += pad;
  1221. }
  1222. return str;
  1223. }
  1224. function StatTimer() {
  1225. this.started = {};
  1226. this.times = [];
  1227. this.enabled = true;
  1228. }
  1229. StatTimer.prototype = {
  1230. time: function StatTimer_time(name) {
  1231. if (!this.enabled) {
  1232. return;
  1233. }
  1234. if (name in this.started) {
  1235. warn('Timer is already running for ' + name);
  1236. }
  1237. this.started[name] = Date.now();
  1238. },
  1239. timeEnd: function StatTimer_timeEnd(name) {
  1240. if (!this.enabled) {
  1241. return;
  1242. }
  1243. if (!(name in this.started)) {
  1244. warn('Timer has not been started for ' + name);
  1245. }
  1246. this.times.push({
  1247. 'name': name,
  1248. 'start': this.started[name],
  1249. 'end': Date.now()
  1250. });
  1251. // Remove timer from started so it can be called again.
  1252. delete this.started[name];
  1253. },
  1254. toString: function StatTimer_toString() {
  1255. var i, ii;
  1256. var times = this.times;
  1257. var out = '';
  1258. // Find the longest name for padding purposes.
  1259. var longest = 0;
  1260. for (i = 0, ii = times.length; i < ii; ++i) {
  1261. var name = times[i]['name'];
  1262. if (name.length > longest) {
  1263. longest = name.length;
  1264. }
  1265. }
  1266. for (i = 0, ii = times.length; i < ii; ++i) {
  1267. var span = times[i];
  1268. var duration = span.end - span.start;
  1269. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1270. }
  1271. return out;
  1272. }
  1273. };
  1274. return StatTimer;
  1275. })();
  1276. PDFJS.createBlob = function createBlob(data, contentType) {
  1277. if (typeof Blob !== 'undefined') {
  1278. return new Blob([data], { type: contentType });
  1279. }
  1280. // Blob builder is deprecated in FF14 and removed in FF18.
  1281. var bb = new MozBlobBuilder();
  1282. bb.append(data);
  1283. return bb.getBlob(contentType);
  1284. };
  1285. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1286. // Blob/createObjectURL is not available, falling back to data schema.
  1287. var digits =
  1288. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1289. return function createObjectURL(data, contentType) {
  1290. if (!PDFJS.disableCreateObjectURL &&
  1291. typeof URL !== 'undefined' && URL.createObjectURL) {
  1292. var blob = PDFJS.createBlob(data, contentType);
  1293. return URL.createObjectURL(blob);
  1294. }
  1295. var buffer = 'data:' + contentType + ';base64,';
  1296. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1297. var b1 = data[i] & 0xFF;
  1298. var b2 = data[i + 1] & 0xFF;
  1299. var b3 = data[i + 2] & 0xFF;
  1300. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1301. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1302. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1303. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1304. }
  1305. return buffer;
  1306. };
  1307. })();
  1308. function MessageHandler(name, comObj) {
  1309. this.name = name;
  1310. this.comObj = comObj;
  1311. this.callbackIndex = 1;
  1312. this.postMessageTransfers = true;
  1313. var callbacksCapabilities = this.callbacksCapabilities = {};
  1314. var ah = this.actionHandler = {};
  1315. ah['console_log'] = [function ahConsoleLog(data) {
  1316. console.log.apply(console, data);
  1317. }];
  1318. ah['console_error'] = [function ahConsoleError(data) {
  1319. console.error.apply(console, data);
  1320. }];
  1321. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1322. UnsupportedManager.notify(data);
  1323. }];
  1324. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1325. var data = event.data;
  1326. if (data.isReply) {
  1327. var callbackId = data.callbackId;
  1328. if (data.callbackId in callbacksCapabilities) {
  1329. var callback = callbacksCapabilities[callbackId];
  1330. delete callbacksCapabilities[callbackId];
  1331. if ('error' in data) {
  1332. callback.reject(data.error);
  1333. } else {
  1334. callback.resolve(data.data);
  1335. }
  1336. } else {
  1337. error('Cannot resolve callback ' + callbackId);
  1338. }
  1339. } else if (data.action in ah) {
  1340. var action = ah[data.action];
  1341. if (data.callbackId) {
  1342. Promise.resolve().then(function () {
  1343. return action[0].call(action[1], data.data);
  1344. }).then(function (result) {
  1345. comObj.postMessage({
  1346. isReply: true,
  1347. callbackId: data.callbackId,
  1348. data: result
  1349. });
  1350. }, function (reason) {
  1351. comObj.postMessage({
  1352. isReply: true,
  1353. callbackId: data.callbackId,
  1354. error: reason
  1355. });
  1356. });
  1357. } else {
  1358. action[0].call(action[1], data.data);
  1359. }
  1360. } else {
  1361. error('Unknown action from worker: ' + data.action);
  1362. }
  1363. };
  1364. }
  1365. MessageHandler.prototype = {
  1366. on: function messageHandlerOn(actionName, handler, scope) {
  1367. var ah = this.actionHandler;
  1368. if (ah[actionName]) {
  1369. error('There is already an actionName called "' + actionName + '"');
  1370. }
  1371. ah[actionName] = [handler, scope];
  1372. },
  1373. /**
  1374. * Sends a message to the comObj to invoke the action with the supplied data.
  1375. * @param {String} actionName Action to call.
  1376. * @param {JSON} data JSON data to send.
  1377. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1378. */
  1379. send: function messageHandlerSend(actionName, data, transfers) {
  1380. var message = {
  1381. action: actionName,
  1382. data: data
  1383. };
  1384. this.postMessage(message, transfers);
  1385. },
  1386. /**
  1387. * Sends a message to the comObj to invoke the action with the supplied data.
  1388. * Expects that other side will callback with the response.
  1389. * @param {String} actionName Action to call.
  1390. * @param {JSON} data JSON data to send.
  1391. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1392. * @returns {Promise} Promise to be resolved with response data.
  1393. */
  1394. sendWithPromise:
  1395. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1396. var callbackId = this.callbackIndex++;
  1397. var message = {
  1398. action: actionName,
  1399. data: data,
  1400. callbackId: callbackId
  1401. };
  1402. var capability = createPromiseCapability();
  1403. this.callbacksCapabilities[callbackId] = capability;
  1404. try {
  1405. this.postMessage(message, transfers);
  1406. } catch (e) {
  1407. capability.reject(e);
  1408. }
  1409. return capability.promise;
  1410. },
  1411. /**
  1412. * Sends raw message to the comObj.
  1413. * @private
  1414. * @param message {Object} Raw message.
  1415. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1416. */
  1417. postMessage: function (message, transfers) {
  1418. if (transfers && this.postMessageTransfers) {
  1419. this.comObj.postMessage(message, transfers);
  1420. } else {
  1421. this.comObj.postMessage(message);
  1422. }
  1423. }
  1424. };
  1425. function loadJpegStream(id, imageUrl, objs) {
  1426. var img = new Image();
  1427. img.onload = (function loadJpegStream_onloadClosure() {
  1428. objs.resolve(id, img);
  1429. });
  1430. img.onerror = (function loadJpegStream_onerrorClosure() {
  1431. objs.resolve(id, null);
  1432. warn('Error during JPEG image loading');
  1433. });
  1434. img.src = imageUrl;
  1435. }
  1436. /**
  1437. * The maximum allowed image size in total pixels e.g. width * height. Images
  1438. * above this value will not be drawn. Use -1 for no limit.
  1439. * @var {number}
  1440. */
  1441. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1442. -1 : PDFJS.maxImageSize);
  1443. /**
  1444. * The url of where the predefined Adobe CMaps are located. Include trailing
  1445. * slash.
  1446. * @var {string}
  1447. */
  1448. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1449. /**
  1450. * Specifies if CMaps are binary packed.
  1451. * @var {boolean}
  1452. */
  1453. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1454. /*
  1455. * By default fonts are converted to OpenType fonts and loaded via font face
  1456. * rules. If disabled, the font will be rendered using a built in font renderer
  1457. * that constructs the glyphs with primitive path commands.
  1458. * @var {boolean}
  1459. */
  1460. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1461. false : PDFJS.disableFontFace);
  1462. /**
  1463. * Path for image resources, mainly for annotation icons. Include trailing
  1464. * slash.
  1465. * @var {string}
  1466. */
  1467. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1468. '' : PDFJS.imageResourcesPath);
  1469. /**
  1470. * Disable the web worker and run all code on the main thread. This will happen
  1471. * automatically if the browser doesn't support workers or sending typed arrays
  1472. * to workers.
  1473. * @var {boolean}
  1474. */
  1475. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1476. false : PDFJS.disableWorker);
  1477. /**
  1478. * Path and filename of the worker file. Required when the worker is enabled in
  1479. * development mode. If unspecified in the production build, the worker will be
  1480. * loaded based on the location of the pdf.js file.
  1481. * @var {string}
  1482. */
  1483. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1484. /**
  1485. * Disable range request loading of PDF files. When enabled and if the server
  1486. * supports partial content requests then the PDF will be fetched in chunks.
  1487. * Enabled (false) by default.
  1488. * @var {boolean}
  1489. */
  1490. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1491. false : PDFJS.disableRange);
  1492. /**
  1493. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1494. * will automatically keep fetching more data even if it isn't needed to display
  1495. * the current page. This default behavior can be disabled.
  1496. * @var {boolean}
  1497. */
  1498. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1499. false : PDFJS.disableAutoFetch);
  1500. /**
  1501. * Enables special hooks for debugging PDF.js.
  1502. * @var {boolean}
  1503. */
  1504. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1505. /**
  1506. * Enables transfer usage in postMessage for ArrayBuffers.
  1507. * @var {boolean}
  1508. */
  1509. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1510. true : PDFJS.postMessageTransfers);
  1511. /**
  1512. * Disables URL.createObjectURL usage.
  1513. * @var {boolean}
  1514. */
  1515. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1516. false : PDFJS.disableCreateObjectURL);
  1517. /**
  1518. * Disables WebGL usage.
  1519. * @var {boolean}
  1520. */
  1521. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1522. true : PDFJS.disableWebGL);
  1523. /**
  1524. * Enables CSS only zooming.
  1525. * @var {boolean}
  1526. */
  1527. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1528. false : PDFJS.useOnlyCssZoom);
  1529. /**
  1530. * Controls the logging level.
  1531. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1532. * - errors
  1533. * - warnings [default]
  1534. * - infos
  1535. * @var {number}
  1536. */
  1537. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1538. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1539. /**
  1540. * The maximum supported canvas size in total pixels e.g. width * height.
  1541. * The default value is 4096 * 4096. Use -1 for no limit.
  1542. * @var {number}
  1543. */
  1544. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1545. 16777216 : PDFJS.maxCanvasPixels);
  1546. /**
  1547. * Document initialization / loading parameters object.
  1548. *
  1549. * @typedef {Object} DocumentInitParameters
  1550. * @property {string} url - The URL of the PDF.
  1551. * @property {TypedArray} data - A typed array with PDF data.
  1552. * @property {Object} httpHeaders - Basic authentication headers.
  1553. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1554. * Access-Control requests should be made using credentials such as cookies
  1555. * or authorization headers. The default is false.
  1556. * @property {string} password - For decrypting password-protected PDFs.
  1557. * @property {TypedArray} initialData - A typed array with the first portion or
  1558. * all of the pdf data. Used by the extension since some data is already
  1559. * loaded before the switch to range requests.
  1560. */
  1561. /**
  1562. * @typedef {Object} PDFDocumentStats
  1563. * @property {Array} streamTypes - Used stream types in the document (an item
  1564. * is set to true if specific stream ID was used in the document).
  1565. * @property {Array} fontTypes - Used font type in the document (an item is set
  1566. * to true if specific font ID was used in the document).
  1567. */
  1568. /**
  1569. * This is the main entry point for loading a PDF and interacting with it.
  1570. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1571. * is used, which means it must follow the same origin rules that any XHR does
  1572. * e.g. No cross domain requests without CORS.
  1573. *
  1574. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  1575. * where a PDF is located, a typed array (Uint8Array) already populated with
  1576. * data or parameter object.
  1577. *
  1578. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  1579. * to manually serve range requests for data in the PDF. See viewer.js for
  1580. * an example of pdfDataRangeTransport's interface.
  1581. *
  1582. * @param {function} passwordCallback is optional. It is used to request a
  1583. * password if wrong or no password was provided. The callback receives two
  1584. * parameters: function that needs to be called with new password and reason
  1585. * (see {PasswordResponses}).
  1586. *
  1587. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  1588. * object.
  1589. */
  1590. PDFJS.getDocument = function getDocument(source,
  1591. pdfDataRangeTransport,
  1592. passwordCallback,
  1593. progressCallback) {
  1594. var workerInitializedCapability, workerReadyCapability, transport;
  1595. if (typeof source === 'string') {
  1596. source = { url: source };
  1597. } else if (isArrayBuffer(source)) {
  1598. source = { data: source };
  1599. } else if (typeof source !== 'object') {
  1600. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1601. 'string or a parameter object');
  1602. }
  1603. if (!source.url && !source.data) {
  1604. error('Invalid parameter array, need either .data or .url');
  1605. }
  1606. // copy/use all keys as is except 'url' -- full path is required
  1607. var params = {};
  1608. for (var key in source) {
  1609. if (key === 'url' && typeof window !== 'undefined') {
  1610. params[key] = combineUrl(window.location.href, source[key]);
  1611. continue;
  1612. }
  1613. params[key] = source[key];
  1614. }
  1615. workerInitializedCapability = createPromiseCapability();
  1616. workerReadyCapability = createPromiseCapability();
  1617. transport = new WorkerTransport(workerInitializedCapability,
  1618. workerReadyCapability, pdfDataRangeTransport,
  1619. progressCallback);
  1620. workerInitializedCapability.promise.then(function transportInitialized() {
  1621. transport.passwordCallback = passwordCallback;
  1622. transport.fetchDocument(params);
  1623. });
  1624. return workerReadyCapability.promise;
  1625. };
  1626. /**
  1627. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1628. * properties that can be read synchronously.
  1629. * @class
  1630. */
  1631. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1632. function PDFDocumentProxy(pdfInfo, transport) {
  1633. this.pdfInfo = pdfInfo;
  1634. this.transport = transport;
  1635. }
  1636. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1637. /**
  1638. * @return {number} Total number of pages the PDF contains.
  1639. */
  1640. get numPages() {
  1641. return this.pdfInfo.numPages;
  1642. },
  1643. /**
  1644. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1645. * unique.
  1646. */
  1647. get fingerprint() {
  1648. return this.pdfInfo.fingerprint;
  1649. },
  1650. /**
  1651. * @param {number} pageNumber The page number to get. The first page is 1.
  1652. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1653. * object.
  1654. */
  1655. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1656. return this.transport.getPage(pageNumber);
  1657. },
  1658. /**
  1659. * @param {{num: number, gen: number}} ref The page reference. Must have
  1660. * the 'num' and 'gen' properties.
  1661. * @return {Promise} A promise that is resolved with the page index that is
  1662. * associated with the reference.
  1663. */
  1664. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1665. return this.transport.getPageIndex(ref);
  1666. },
  1667. /**
  1668. * @return {Promise} A promise that is resolved with a lookup table for
  1669. * mapping named destinations to reference numbers.
  1670. */
  1671. getDestinations: function PDFDocumentProxy_getDestinations() {
  1672. return this.transport.getDestinations();
  1673. },
  1674. /**
  1675. * @return {Promise} A promise that is resolved with a lookup table for
  1676. * mapping named attachments to their content.
  1677. */
  1678. getAttachments: function PDFDocumentProxy_getAttachments() {
  1679. return this.transport.getAttachments();
  1680. },
  1681. /**
  1682. * @return {Promise} A promise that is resolved with an array of all the
  1683. * JavaScript strings in the name tree.
  1684. */
  1685. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1686. return this.transport.getJavaScript();
  1687. },
  1688. /**
  1689. * @return {Promise} A promise that is resolved with an {Array} that is a
  1690. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1691. * [
  1692. * {
  1693. * title: string,
  1694. * bold: boolean,
  1695. * italic: boolean,
  1696. * color: rgb array,
  1697. * dest: dest obj,
  1698. * items: array of more items like this
  1699. * },
  1700. * ...
  1701. * ].
  1702. */
  1703. getOutline: function PDFDocumentProxy_getOutline() {
  1704. return this.transport.getOutline();
  1705. },
  1706. /**
  1707. * @return {Promise} A promise that is resolved with an {Object} that has
  1708. * info and metadata properties. Info is an {Object} filled with anything
  1709. * available in the information dictionary and similarly metadata is a
  1710. * {Metadata} object with information from the metadata section of the PDF.
  1711. */
  1712. getMetadata: function PDFDocumentProxy_getMetadata() {
  1713. return this.transport.getMetadata();
  1714. },
  1715. /**
  1716. * @return {Promise} A promise that is resolved with a TypedArray that has
  1717. * the raw data from the PDF.
  1718. */
  1719. getData: function PDFDocumentProxy_getData() {
  1720. return this.transport.getData();
  1721. },
  1722. /**
  1723. * @return {Promise} A promise that is resolved when the document's data
  1724. * is loaded. It is resolved with an {Object} that contains the length
  1725. * property that indicates size of the PDF data in bytes.
  1726. */
  1727. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1728. return this.transport.downloadInfoCapability.promise;
  1729. },
  1730. /**
  1731. * @returns {Promise} A promise this is resolved with current stats about
  1732. * document structures (see {@link PDFDocumentStats}).
  1733. */
  1734. getStats: function PDFDocumentProxy_getStats() {
  1735. return this.transport.getStats();
  1736. },
  1737. /**
  1738. * Cleans up resources allocated by the document, e.g. created @font-face.
  1739. */
  1740. cleanup: function PDFDocumentProxy_cleanup() {
  1741. this.transport.startCleanup();
  1742. },
  1743. /**
  1744. * Destroys current document instance and terminates worker.
  1745. */
  1746. destroy: function PDFDocumentProxy_destroy() {
  1747. this.transport.destroy();
  1748. }
  1749. };
  1750. return PDFDocumentProxy;
  1751. })();
  1752. /**
  1753. * Page text content.
  1754. *
  1755. * @typedef {Object} TextContent
  1756. * @property {array} items - array of {@link TextItem}
  1757. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1758. * name.
  1759. */
  1760. /**
  1761. * Page text content part.
  1762. *
  1763. * @typedef {Object} TextItem
  1764. * @property {string} str - text content.
  1765. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1766. * @property {array} transform - transformation matrix.
  1767. * @property {number} width - width in device space.
  1768. * @property {number} height - height in device space.
  1769. * @property {string} fontName - font name used by pdf.js for converted font.
  1770. */
  1771. /**
  1772. * Text style.
  1773. *
  1774. * @typedef {Object} TextStyle
  1775. * @property {number} ascent - font ascent.
  1776. * @property {number} descent - font descent.
  1777. * @property {boolean} vertical - text is in vertical mode.
  1778. * @property {string} fontFamily - possible font family
  1779. */
  1780. /**
  1781. * Page render parameters.
  1782. *
  1783. * @typedef {Object} RenderParameters
  1784. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1785. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1786. * calling of PDFPage.getViewport method.
  1787. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1788. * (default value is 'display').
  1789. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1790. * endLayout and appendImage functions.
  1791. * @property {function} continueCallback - (optional) A function that will be
  1792. * called each time the rendering is paused. To continue
  1793. * rendering call the function that is the first argument
  1794. * to the callback.
  1795. */
  1796. /**
  1797. * PDF page operator list.
  1798. *
  1799. * @typedef {Object} PDFOperatorList
  1800. * @property {Array} fnArray - Array containing the operator functions.
  1801. * @property {Array} argsArray - Array containing the arguments of the
  1802. * functions.
  1803. */
  1804. /**
  1805. * Proxy to a PDFPage in the worker thread.
  1806. * @class
  1807. */
  1808. var PDFPageProxy = (function PDFPageProxyClosure() {
  1809. function PDFPageProxy(pageIndex, pageInfo, transport) {
  1810. this.pageIndex = pageIndex;
  1811. this.pageInfo = pageInfo;
  1812. this.transport = transport;
  1813. this.stats = new StatTimer();
  1814. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  1815. this.commonObjs = transport.commonObjs;
  1816. this.objs = new PDFObjects();
  1817. this.cleanupAfterRender = false;
  1818. this.pendingDestroy = false;
  1819. this.intentStates = {};
  1820. }
  1821. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  1822. /**
  1823. * @return {number} Page number of the page. First page is 1.
  1824. */
  1825. get pageNumber() {
  1826. return this.pageIndex + 1;
  1827. },
  1828. /**
  1829. * @return {number} The number of degrees the page is rotated clockwise.
  1830. */
  1831. get rotate() {
  1832. return this.pageInfo.rotate;
  1833. },
  1834. /**
  1835. * @return {Object} The reference that points to this page. It has 'num' and
  1836. * 'gen' properties.
  1837. */
  1838. get ref() {
  1839. return this.pageInfo.ref;
  1840. },
  1841. /**
  1842. * @return {Array} An array of the visible portion of the PDF page in the
  1843. * user space units - [x1, y1, x2, y2].
  1844. */
  1845. get view() {
  1846. return this.pageInfo.view;
  1847. },
  1848. /**
  1849. * @param {number} scale The desired scale of the viewport.
  1850. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  1851. * defaults to the page rotation.
  1852. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  1853. * along with transforms required for rendering.
  1854. */
  1855. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  1856. if (arguments.length < 2) {
  1857. rotate = this.rotate;
  1858. }
  1859. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  1860. },
  1861. /**
  1862. * @return {Promise} A promise that is resolved with an {Array} of the
  1863. * annotation objects.
  1864. */
  1865. getAnnotations: function PDFPageProxy_getAnnotations() {
  1866. if (this.annotationsPromise) {
  1867. return this.annotationsPromise;
  1868. }
  1869. var promise = this.transport.getAnnotations(this.pageIndex);
  1870. this.annotationsPromise = promise;
  1871. return promise;
  1872. },
  1873. /**
  1874. * Begins the process of rendering a page to the desired context.
  1875. * @param {RenderParameters} params Page render parameters.
  1876. * @return {RenderTask} An object that contains the promise, which
  1877. * is resolved when the page finishes rendering.
  1878. */
  1879. render: function PDFPageProxy_render(params) {
  1880. var stats = this.stats;
  1881. stats.time('Overall');
  1882. // If there was a pending destroy cancel it so no cleanup happens during
  1883. // this call to render.
  1884. this.pendingDestroy = false;
  1885. var renderingIntent = ('intent' in params ?
  1886. (params.intent == 'print' ? 'print' : 'display') : '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. this.processingType3 = glyph;
  4058. this.save();
  4059. ctx.scale(fontSize, fontSize);
  4060. ctx.transform.apply(ctx, fontMatrix);
  4061. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4062. this.executeOperatorList(operatorList);
  4063. this.restore();
  4064. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4065. width = ((transformed[0] * fontSize + charSpacing) * fontDirection);
  4066. ctx.translate(width, 0);
  4067. current.x += width * textHScale;
  4068. }
  4069. ctx.restore();
  4070. this.processingType3 = null;
  4071. },
  4072. // Type3 fonts
  4073. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4074. // We can safely ignore this since the width should be the same
  4075. // as the width in the Widths array.
  4076. },
  4077. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4078. yWidth,
  4079. llx,
  4080. lly,
  4081. urx,
  4082. ury) {
  4083. // TODO According to the spec we're also suppose to ignore any operators
  4084. // that set color or include images while processing this type3 font.
  4085. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4086. this.clip();
  4087. this.endPath();
  4088. },
  4089. // Color
  4090. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4091. var pattern;
  4092. if (IR[0] === 'TilingPattern') {
  4093. var color = IR[1];
  4094. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4095. this.commonObjs, this.baseTransform);
  4096. } else {
  4097. pattern = getShadingPatternFromIR(IR);
  4098. }
  4099. return pattern;
  4100. },
  4101. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4102. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4103. },
  4104. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4105. this.current.fillColor = this.getColorN_Pattern(arguments);
  4106. },
  4107. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4108. var color = Util.makeCssRgb(arguments);
  4109. this.ctx.strokeStyle = color;
  4110. this.current.strokeColor = color;
  4111. },
  4112. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4113. var color = Util.makeCssRgb(arguments);
  4114. this.ctx.fillStyle = color;
  4115. this.current.fillColor = color;
  4116. },
  4117. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4118. var ctx = this.ctx;
  4119. this.save();
  4120. var pattern = getShadingPatternFromIR(patternIR);
  4121. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4122. var inv = ctx.mozCurrentTransformInverse;
  4123. if (inv) {
  4124. var canvas = ctx.canvas;
  4125. var width = canvas.width;
  4126. var height = canvas.height;
  4127. var bl = Util.applyTransform([0, 0], inv);
  4128. var br = Util.applyTransform([0, height], inv);
  4129. var ul = Util.applyTransform([width, 0], inv);
  4130. var ur = Util.applyTransform([width, height], inv);
  4131. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4132. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4133. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4134. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4135. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4136. } else {
  4137. // HACK to draw the gradient onto an infinite rectangle.
  4138. // PDF gradients are drawn across the entire image while
  4139. // Canvas only allows gradients to be drawn in a rectangle
  4140. // The following bug should allow us to remove this.
  4141. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4142. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4143. }
  4144. this.restore();
  4145. },
  4146. // Images
  4147. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4148. error('Should not call beginInlineImage');
  4149. },
  4150. beginImageData: function CanvasGraphics_beginImageData() {
  4151. error('Should not call beginImageData');
  4152. },
  4153. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4154. bbox) {
  4155. this.save();
  4156. this.baseTransformStack.push(this.baseTransform);
  4157. if (isArray(matrix) && 6 === matrix.length) {
  4158. this.transform.apply(this, matrix);
  4159. }
  4160. this.baseTransform = this.ctx.mozCurrentTransform;
  4161. if (isArray(bbox) && 4 === bbox.length) {
  4162. var width = bbox[2] - bbox[0];
  4163. var height = bbox[3] - bbox[1];
  4164. this.ctx.rect(bbox[0], bbox[1], width, height);
  4165. this.clip();
  4166. this.endPath();
  4167. }
  4168. },
  4169. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4170. this.restore();
  4171. this.baseTransform = this.baseTransformStack.pop();
  4172. },
  4173. beginGroup: function CanvasGraphics_beginGroup(group) {
  4174. this.save();
  4175. var currentCtx = this.ctx;
  4176. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4177. // group results aren't usually that different and they even have tools
  4178. // that ignore this setting. Notes from Rik on implmenting:
  4179. // - When you encounter an transparency group, create a new canvas with
  4180. // the dimensions of the bbox
  4181. // - copy the content from the previous canvas to the new canvas
  4182. // - draw as usual
  4183. // - remove the backdrop alpha:
  4184. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4185. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4186. // backdrop
  4187. // - remove background color:
  4188. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4189. if (!group.isolated) {
  4190. info('TODO: Support non-isolated groups.');
  4191. }
  4192. // TODO knockout - supposedly possible with the clever use of compositing
  4193. // modes.
  4194. if (group.knockout) {
  4195. warn('Knockout groups not supported.');
  4196. }
  4197. var currentTransform = currentCtx.mozCurrentTransform;
  4198. if (group.matrix) {
  4199. currentCtx.transform.apply(currentCtx, group.matrix);
  4200. }
  4201. assert(group.bbox, 'Bounding box is required.');
  4202. // Based on the current transform figure out how big the bounding box
  4203. // will actually be.
  4204. var bounds = Util.getAxialAlignedBoundingBox(
  4205. group.bbox,
  4206. currentCtx.mozCurrentTransform);
  4207. // Clip the bounding box to the current canvas.
  4208. var canvasBounds = [0,
  4209. 0,
  4210. currentCtx.canvas.width,
  4211. currentCtx.canvas.height];
  4212. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4213. // Use ceil in case we're between sizes so we don't create canvas that is
  4214. // too small and make the canvas at least 1x1 pixels.
  4215. var offsetX = Math.floor(bounds[0]);
  4216. var offsetY = Math.floor(bounds[1]);
  4217. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4218. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4219. var scaleX = 1, scaleY = 1;
  4220. if (drawnWidth > MAX_GROUP_SIZE) {
  4221. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4222. drawnWidth = MAX_GROUP_SIZE;
  4223. }
  4224. if (drawnHeight > MAX_GROUP_SIZE) {
  4225. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4226. drawnHeight = MAX_GROUP_SIZE;
  4227. }
  4228. var cacheId = 'groupAt' + this.groupLevel;
  4229. if (group.smask) {
  4230. // Using two cache entries is case if masks are used one after another.
  4231. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4232. }
  4233. var scratchCanvas = CachedCanvases.getCanvas(
  4234. cacheId, drawnWidth, drawnHeight, true);
  4235. var groupCtx = scratchCanvas.context;
  4236. // Since we created a new canvas that is just the size of the bounding box
  4237. // we have to translate the group ctx.
  4238. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4239. groupCtx.translate(-offsetX, -offsetY);
  4240. groupCtx.transform.apply(groupCtx, currentTransform);
  4241. if (group.smask) {
  4242. // Saving state and cached mask to be used in setGState.
  4243. this.smaskStack.push({
  4244. canvas: scratchCanvas.canvas,
  4245. context: groupCtx,
  4246. offsetX: offsetX,
  4247. offsetY: offsetY,
  4248. scaleX: scaleX,
  4249. scaleY: scaleY,
  4250. subtype: group.smask.subtype,
  4251. backdrop: group.smask.backdrop
  4252. });
  4253. } else {
  4254. // Setup the current ctx so when the group is popped we draw it at the
  4255. // right location.
  4256. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4257. currentCtx.translate(offsetX, offsetY);
  4258. currentCtx.scale(scaleX, scaleY);
  4259. }
  4260. // The transparency group inherits all off the current graphics state
  4261. // except the blend mode, soft mask, and alpha constants.
  4262. copyCtxState(currentCtx, groupCtx);
  4263. this.ctx = groupCtx;
  4264. this.setGState([
  4265. ['BM', 'Normal'],
  4266. ['ca', 1],
  4267. ['CA', 1]
  4268. ]);
  4269. this.groupStack.push(currentCtx);
  4270. this.groupLevel++;
  4271. },
  4272. endGroup: function CanvasGraphics_endGroup(group) {
  4273. this.groupLevel--;
  4274. var groupCtx = this.ctx;
  4275. this.ctx = this.groupStack.pop();
  4276. // Turn off image smoothing to avoid sub pixel interpolation which can
  4277. // look kind of blurry for some pdfs.
  4278. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4279. this.ctx.imageSmoothingEnabled = false;
  4280. } else {
  4281. this.ctx.mozImageSmoothingEnabled = false;
  4282. }
  4283. if (group.smask) {
  4284. this.tempSMask = this.smaskStack.pop();
  4285. } else {
  4286. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4287. }
  4288. this.restore();
  4289. },
  4290. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4291. this.save();
  4292. this.current = new CanvasExtraState();
  4293. },
  4294. endAnnotations: function CanvasGraphics_endAnnotations() {
  4295. this.restore();
  4296. },
  4297. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4298. matrix) {
  4299. this.save();
  4300. if (isArray(rect) && 4 === rect.length) {
  4301. var width = rect[2] - rect[0];
  4302. var height = rect[3] - rect[1];
  4303. this.ctx.rect(rect[0], rect[1], width, height);
  4304. this.clip();
  4305. this.endPath();
  4306. }
  4307. this.transform.apply(this, transform);
  4308. this.transform.apply(this, matrix);
  4309. },
  4310. endAnnotation: function CanvasGraphics_endAnnotation() {
  4311. this.restore();
  4312. },
  4313. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4314. var domImage = this.objs.get(objId);
  4315. if (!domImage) {
  4316. warn('Dependent image isn\'t ready yet');
  4317. return;
  4318. }
  4319. this.save();
  4320. var ctx = this.ctx;
  4321. // scale the image to the unit square
  4322. ctx.scale(1 / w, -1 / h);
  4323. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4324. 0, -h, w, h);
  4325. if (this.imageLayer) {
  4326. var currentTransform = ctx.mozCurrentTransformInverse;
  4327. var position = this.getCanvasPosition(0, 0);
  4328. this.imageLayer.appendImage({
  4329. objId: objId,
  4330. left: position[0],
  4331. top: position[1],
  4332. width: w / currentTransform[0],
  4333. height: h / currentTransform[3]
  4334. });
  4335. }
  4336. this.restore();
  4337. },
  4338. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4339. var ctx = this.ctx;
  4340. var width = img.width, height = img.height;
  4341. var glyph = this.processingType3;
  4342. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  4343. var MAX_SIZE_TO_COMPILE = 1000;
  4344. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4345. glyph.compiled =
  4346. compileType3Glyph({data: img.data, width: width, height: height});
  4347. } else {
  4348. glyph.compiled = null;
  4349. }
  4350. }
  4351. if (glyph && glyph.compiled) {
  4352. glyph.compiled(ctx);
  4353. return;
  4354. }
  4355. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4356. var maskCtx = maskCanvas.context;
  4357. maskCtx.save();
  4358. putBinaryImageMask(maskCtx, img);
  4359. maskCtx.globalCompositeOperation = 'source-in';
  4360. var fillColor = this.current.fillColor;
  4361. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4362. fillColor.type === 'Pattern') ?
  4363. fillColor.getPattern(maskCtx, this) : fillColor;
  4364. maskCtx.fillRect(0, 0, width, height);
  4365. maskCtx.restore();
  4366. this.paintInlineImageXObject(maskCanvas.canvas);
  4367. },
  4368. paintImageMaskXObjectRepeat:
  4369. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4370. scaleY, positions) {
  4371. var width = imgData.width;
  4372. var height = imgData.height;
  4373. var ctx = this.ctx;
  4374. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4375. var maskCtx = maskCanvas.context;
  4376. maskCtx.save();
  4377. putBinaryImageMask(maskCtx, imgData);
  4378. maskCtx.globalCompositeOperation = 'source-in';
  4379. var fillColor = this.current.fillColor;
  4380. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4381. fillColor.type === 'Pattern') ?
  4382. fillColor.getPattern(maskCtx, this) : fillColor;
  4383. maskCtx.fillRect(0, 0, width, height);
  4384. maskCtx.restore();
  4385. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4386. ctx.save();
  4387. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4388. ctx.scale(1, -1);
  4389. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4390. 0, -1, 1, 1);
  4391. ctx.restore();
  4392. }
  4393. },
  4394. paintImageMaskXObjectGroup:
  4395. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4396. var ctx = this.ctx;
  4397. for (var i = 0, ii = images.length; i < ii; i++) {
  4398. var image = images[i];
  4399. var width = image.width, height = image.height;
  4400. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4401. var maskCtx = maskCanvas.context;
  4402. maskCtx.save();
  4403. putBinaryImageMask(maskCtx, image);
  4404. maskCtx.globalCompositeOperation = 'source-in';
  4405. var fillColor = this.current.fillColor;
  4406. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4407. fillColor.type === 'Pattern') ?
  4408. fillColor.getPattern(maskCtx, this) : fillColor;
  4409. maskCtx.fillRect(0, 0, width, height);
  4410. maskCtx.restore();
  4411. ctx.save();
  4412. ctx.transform.apply(ctx, image.transform);
  4413. ctx.scale(1, -1);
  4414. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4415. 0, -1, 1, 1);
  4416. ctx.restore();
  4417. }
  4418. },
  4419. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4420. var imgData = this.objs.get(objId);
  4421. if (!imgData) {
  4422. warn('Dependent image isn\'t ready yet');
  4423. return;
  4424. }
  4425. this.paintInlineImageXObject(imgData);
  4426. },
  4427. paintImageXObjectRepeat:
  4428. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4429. positions) {
  4430. var imgData = this.objs.get(objId);
  4431. if (!imgData) {
  4432. warn('Dependent image isn\'t ready yet');
  4433. return;
  4434. }
  4435. var width = imgData.width;
  4436. var height = imgData.height;
  4437. var map = [];
  4438. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4439. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4440. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4441. }
  4442. this.paintInlineImageXObjectGroup(imgData, map);
  4443. },
  4444. paintInlineImageXObject:
  4445. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4446. var width = imgData.width;
  4447. var height = imgData.height;
  4448. var ctx = this.ctx;
  4449. this.save();
  4450. // scale the image to the unit square
  4451. ctx.scale(1 / width, -1 / height);
  4452. var currentTransform = ctx.mozCurrentTransformInverse;
  4453. var a = currentTransform[0], b = currentTransform[1];
  4454. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4455. var c = currentTransform[2], d = currentTransform[3];
  4456. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4457. var imgToPaint, tmpCanvas;
  4458. // instanceof HTMLElement does not work in jsdom node.js module
  4459. if (imgData instanceof HTMLElement || !imgData.data) {
  4460. imgToPaint = imgData;
  4461. } else {
  4462. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4463. var tmpCtx = tmpCanvas.context;
  4464. putBinaryImageData(tmpCtx, imgData);
  4465. imgToPaint = tmpCanvas.canvas;
  4466. }
  4467. var paintWidth = width, paintHeight = height;
  4468. var tmpCanvasId = 'prescale1';
  4469. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4470. // pixels during drawImage operation, painting on the temporary canvas(es)
  4471. // that are twice smaller in size
  4472. while ((widthScale > 2 && paintWidth > 1) ||
  4473. (heightScale > 2 && paintHeight > 1)) {
  4474. var newWidth = paintWidth, newHeight = paintHeight;
  4475. if (widthScale > 2 && paintWidth > 1) {
  4476. newWidth = Math.ceil(paintWidth / 2);
  4477. widthScale /= paintWidth / newWidth;
  4478. }
  4479. if (heightScale > 2 && paintHeight > 1) {
  4480. newHeight = Math.ceil(paintHeight / 2);
  4481. heightScale /= paintHeight / newHeight;
  4482. }
  4483. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4484. tmpCtx = tmpCanvas.context;
  4485. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4486. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4487. 0, 0, newWidth, newHeight);
  4488. imgToPaint = tmpCanvas.canvas;
  4489. paintWidth = newWidth;
  4490. paintHeight = newHeight;
  4491. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4492. }
  4493. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4494. 0, -height, width, height);
  4495. if (this.imageLayer) {
  4496. var position = this.getCanvasPosition(0, -height);
  4497. this.imageLayer.appendImage({
  4498. imgData: imgData,
  4499. left: position[0],
  4500. top: position[1],
  4501. width: width / currentTransform[0],
  4502. height: height / currentTransform[3]
  4503. });
  4504. }
  4505. this.restore();
  4506. },
  4507. paintInlineImageXObjectGroup:
  4508. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4509. var ctx = this.ctx;
  4510. var w = imgData.width;
  4511. var h = imgData.height;
  4512. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4513. var tmpCtx = tmpCanvas.context;
  4514. putBinaryImageData(tmpCtx, imgData);
  4515. for (var i = 0, ii = map.length; i < ii; i++) {
  4516. var entry = map[i];
  4517. ctx.save();
  4518. ctx.transform.apply(ctx, entry.transform);
  4519. ctx.scale(1, -1);
  4520. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4521. 0, -1, 1, 1);
  4522. if (this.imageLayer) {
  4523. var position = this.getCanvasPosition(entry.x, entry.y);
  4524. this.imageLayer.appendImage({
  4525. imgData: imgData,
  4526. left: position[0],
  4527. top: position[1],
  4528. width: w,
  4529. height: h
  4530. });
  4531. }
  4532. ctx.restore();
  4533. }
  4534. },
  4535. paintSolidColorImageMask:
  4536. function CanvasGraphics_paintSolidColorImageMask() {
  4537. this.ctx.fillRect(0, 0, 1, 1);
  4538. },
  4539. // Marked content
  4540. markPoint: function CanvasGraphics_markPoint(tag) {
  4541. // TODO Marked content.
  4542. },
  4543. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4544. // TODO Marked content.
  4545. },
  4546. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4547. // TODO Marked content.
  4548. },
  4549. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4550. tag, properties) {
  4551. // TODO Marked content.
  4552. },
  4553. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4554. // TODO Marked content.
  4555. },
  4556. // Compatibility
  4557. beginCompat: function CanvasGraphics_beginCompat() {
  4558. // TODO ignore undefined operators (should we do that anyway?)
  4559. },
  4560. endCompat: function CanvasGraphics_endCompat() {
  4561. // TODO stop ignoring undefined operators
  4562. },
  4563. // Helper functions
  4564. consumePath: function CanvasGraphics_consumePath() {
  4565. var ctx = this.ctx;
  4566. if (this.pendingClip) {
  4567. if (this.pendingClip === EO_CLIP) {
  4568. if (ctx.mozFillRule !== undefined) {
  4569. ctx.mozFillRule = 'evenodd';
  4570. ctx.clip();
  4571. ctx.mozFillRule = 'nonzero';
  4572. } else {
  4573. try {
  4574. ctx.clip('evenodd');
  4575. } catch (ex) {
  4576. // shouldn't really happen, but browsers might think differently
  4577. ctx.clip();
  4578. }
  4579. }
  4580. } else {
  4581. ctx.clip();
  4582. }
  4583. this.pendingClip = null;
  4584. }
  4585. ctx.beginPath();
  4586. },
  4587. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4588. var inverse = this.ctx.mozCurrentTransformInverse;
  4589. // max of the current horizontal and vertical scale
  4590. return Math.sqrt(Math.max(
  4591. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4592. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4593. },
  4594. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4595. var transform = this.ctx.mozCurrentTransform;
  4596. return [
  4597. transform[0] * x + transform[2] * y + transform[4],
  4598. transform[1] * x + transform[3] * y + transform[5]
  4599. ];
  4600. }
  4601. };
  4602. for (var op in OPS) {
  4603. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4604. }
  4605. return CanvasGraphics;
  4606. })();
  4607. var WebGLUtils = (function WebGLUtilsClosure() {
  4608. function loadShader(gl, code, shaderType) {
  4609. var shader = gl.createShader(shaderType);
  4610. gl.shaderSource(shader, code);
  4611. gl.compileShader(shader);
  4612. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4613. if (!compiled) {
  4614. var errorMsg = gl.getShaderInfoLog(shader);
  4615. throw new Error('Error during shader compilation: ' + errorMsg);
  4616. }
  4617. return shader;
  4618. }
  4619. function createVertexShader(gl, code) {
  4620. return loadShader(gl, code, gl.VERTEX_SHADER);
  4621. }
  4622. function createFragmentShader(gl, code) {
  4623. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4624. }
  4625. function createProgram(gl, shaders) {
  4626. var program = gl.createProgram();
  4627. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4628. gl.attachShader(program, shaders[i]);
  4629. }
  4630. gl.linkProgram(program);
  4631. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4632. if (!linked) {
  4633. var errorMsg = gl.getProgramInfoLog(program);
  4634. throw new Error('Error during program linking: ' + errorMsg);
  4635. }
  4636. return program;
  4637. }
  4638. function createTexture(gl, image, textureId) {
  4639. gl.activeTexture(textureId);
  4640. var texture = gl.createTexture();
  4641. gl.bindTexture(gl.TEXTURE_2D, texture);
  4642. // Set the parameters so we can render any size image.
  4643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4647. // Upload the image into the texture.
  4648. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4649. return texture;
  4650. }
  4651. var currentGL, currentCanvas;
  4652. function generageGL() {
  4653. if (currentGL) {
  4654. return;
  4655. }
  4656. currentCanvas = document.createElement('canvas');
  4657. currentGL = currentCanvas.getContext('webgl',
  4658. { premultipliedalpha: false });
  4659. }
  4660. var smaskVertexShaderCode = '\
  4661. attribute vec2 a_position; \
  4662. attribute vec2 a_texCoord; \
  4663. \
  4664. uniform vec2 u_resolution; \
  4665. \
  4666. varying vec2 v_texCoord; \
  4667. \
  4668. void main() { \
  4669. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4670. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4671. \
  4672. v_texCoord = a_texCoord; \
  4673. } ';
  4674. var smaskFragmentShaderCode = '\
  4675. precision mediump float; \
  4676. \
  4677. uniform vec4 u_backdrop; \
  4678. uniform int u_subtype; \
  4679. uniform sampler2D u_image; \
  4680. uniform sampler2D u_mask; \
  4681. \
  4682. varying vec2 v_texCoord; \
  4683. \
  4684. void main() { \
  4685. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4686. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4687. if (u_backdrop.a > 0.0) { \
  4688. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4689. u_backdrop.rgb * (1.0 - maskColor.a); \
  4690. } \
  4691. float lum; \
  4692. if (u_subtype == 0) { \
  4693. lum = maskColor.a; \
  4694. } else { \
  4695. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4696. maskColor.b * 0.11; \
  4697. } \
  4698. imageColor.a *= lum; \
  4699. imageColor.rgb *= imageColor.a; \
  4700. gl_FragColor = imageColor; \
  4701. } ';
  4702. var smaskCache = null;
  4703. function initSmaskGL() {
  4704. var canvas, gl;
  4705. generageGL();
  4706. canvas = currentCanvas;
  4707. currentCanvas = null;
  4708. gl = currentGL;
  4709. currentGL = null;
  4710. // setup a GLSL program
  4711. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4712. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4713. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4714. gl.useProgram(program);
  4715. var cache = {};
  4716. cache.gl = gl;
  4717. cache.canvas = canvas;
  4718. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4719. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4720. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4721. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4722. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4723. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4724. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4725. // provide texture coordinates for the rectangle.
  4726. var texCoordBuffer = gl.createBuffer();
  4727. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4728. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4729. 0.0, 0.0,
  4730. 1.0, 0.0,
  4731. 0.0, 1.0,
  4732. 0.0, 1.0,
  4733. 1.0, 0.0,
  4734. 1.0, 1.0]), gl.STATIC_DRAW);
  4735. gl.enableVertexAttribArray(texCoordLocation);
  4736. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4737. gl.uniform1i(texLayerLocation, 0);
  4738. gl.uniform1i(texMaskLocation, 1);
  4739. smaskCache = cache;
  4740. }
  4741. function composeSMask(layer, mask, properties) {
  4742. var width = layer.width, height = layer.height;
  4743. if (!smaskCache) {
  4744. initSmaskGL();
  4745. }
  4746. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4747. canvas.width = width;
  4748. canvas.height = height;
  4749. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4750. gl.uniform2f(cache.resolutionLocation, width, height);
  4751. if (properties.backdrop) {
  4752. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4753. properties.backdrop[1], properties.backdrop[2], 1);
  4754. } else {
  4755. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4756. }
  4757. gl.uniform1i(cache.subtypeLocation,
  4758. properties.subtype === 'Luminosity' ? 1 : 0);
  4759. // Create a textures
  4760. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4761. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4762. // Create a buffer and put a single clipspace rectangle in
  4763. // it (2 triangles)
  4764. var buffer = gl.createBuffer();
  4765. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4766. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4767. 0, 0,
  4768. width, 0,
  4769. 0, height,
  4770. 0, height,
  4771. width, 0,
  4772. width, height]), gl.STATIC_DRAW);
  4773. gl.enableVertexAttribArray(cache.positionLocation);
  4774. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4775. // draw
  4776. gl.clearColor(0, 0, 0, 0);
  4777. gl.enable(gl.BLEND);
  4778. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4779. gl.clear(gl.COLOR_BUFFER_BIT);
  4780. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4781. gl.flush();
  4782. gl.deleteTexture(texture);
  4783. gl.deleteTexture(maskTexture);
  4784. gl.deleteBuffer(buffer);
  4785. return canvas;
  4786. }
  4787. var figuresVertexShaderCode = '\
  4788. attribute vec2 a_position; \
  4789. attribute vec3 a_color; \
  4790. \
  4791. uniform vec2 u_resolution; \
  4792. uniform vec2 u_scale; \
  4793. uniform vec2 u_offset; \
  4794. \
  4795. varying vec4 v_color; \
  4796. \
  4797. void main() { \
  4798. vec2 position = (a_position + u_offset) * u_scale; \
  4799. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  4800. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4801. \
  4802. v_color = vec4(a_color / 255.0, 1.0); \
  4803. } ';
  4804. var figuresFragmentShaderCode = '\
  4805. precision mediump float; \
  4806. \
  4807. varying vec4 v_color; \
  4808. \
  4809. void main() { \
  4810. gl_FragColor = v_color; \
  4811. } ';
  4812. var figuresCache = null;
  4813. function initFiguresGL() {
  4814. var canvas, gl;
  4815. generageGL();
  4816. canvas = currentCanvas;
  4817. currentCanvas = null;
  4818. gl = currentGL;
  4819. currentGL = null;
  4820. // setup a GLSL program
  4821. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  4822. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  4823. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4824. gl.useProgram(program);
  4825. var cache = {};
  4826. cache.gl = gl;
  4827. cache.canvas = canvas;
  4828. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4829. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  4830. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  4831. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4832. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  4833. figuresCache = cache;
  4834. }
  4835. function drawFigures(width, height, backgroundColor, figures, context) {
  4836. if (!figuresCache) {
  4837. initFiguresGL();
  4838. }
  4839. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  4840. canvas.width = width;
  4841. canvas.height = height;
  4842. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4843. gl.uniform2f(cache.resolutionLocation, width, height);
  4844. // count triangle points
  4845. var count = 0;
  4846. var i, ii, rows;
  4847. for (i = 0, ii = figures.length; i < ii; i++) {
  4848. switch (figures[i].type) {
  4849. case 'lattice':
  4850. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  4851. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  4852. break;
  4853. case 'triangles':
  4854. count += figures[i].coords.length;
  4855. break;
  4856. }
  4857. }
  4858. // transfer data
  4859. var coords = new Float32Array(count * 2);
  4860. var colors = new Uint8Array(count * 3);
  4861. var coordsMap = context.coords, colorsMap = context.colors;
  4862. var pIndex = 0, cIndex = 0;
  4863. for (i = 0, ii = figures.length; i < ii; i++) {
  4864. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  4865. switch (figure.type) {
  4866. case 'lattice':
  4867. var cols = figure.verticesPerRow;
  4868. rows = (ps.length / cols) | 0;
  4869. for (var row = 1; row < rows; row++) {
  4870. var offset = row * cols + 1;
  4871. for (var col = 1; col < cols; col++, offset++) {
  4872. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  4873. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  4874. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  4875. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  4876. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  4877. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  4878. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  4879. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  4880. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  4881. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  4882. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  4883. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  4884. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  4885. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  4886. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  4887. coords[pIndex + 6] = coords[pIndex + 2];
  4888. coords[pIndex + 7] = coords[pIndex + 3];
  4889. coords[pIndex + 8] = coords[pIndex + 4];
  4890. coords[pIndex + 9] = coords[pIndex + 5];
  4891. coords[pIndex + 10] = coordsMap[ps[offset]];
  4892. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  4893. colors[cIndex + 9] = colors[cIndex + 3];
  4894. colors[cIndex + 10] = colors[cIndex + 4];
  4895. colors[cIndex + 11] = colors[cIndex + 5];
  4896. colors[cIndex + 12] = colors[cIndex + 6];
  4897. colors[cIndex + 13] = colors[cIndex + 7];
  4898. colors[cIndex + 14] = colors[cIndex + 8];
  4899. colors[cIndex + 15] = colorsMap[cs[offset]];
  4900. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  4901. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  4902. pIndex += 12;
  4903. cIndex += 18;
  4904. }
  4905. }
  4906. break;
  4907. case 'triangles':
  4908. for (var j = 0, jj = ps.length; j < jj; j++) {
  4909. coords[pIndex] = coordsMap[ps[j]];
  4910. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  4911. colors[cIndex] = colorsMap[cs[i]];
  4912. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  4913. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  4914. pIndex += 2;
  4915. cIndex += 3;
  4916. }
  4917. break;
  4918. }
  4919. }
  4920. // draw
  4921. if (backgroundColor) {
  4922. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  4923. backgroundColor[2] / 255, 1.0);
  4924. } else {
  4925. gl.clearColor(0, 0, 0, 0);
  4926. }
  4927. gl.clear(gl.COLOR_BUFFER_BIT);
  4928. var coordsBuffer = gl.createBuffer();
  4929. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  4930. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  4931. gl.enableVertexAttribArray(cache.positionLocation);
  4932. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4933. var colorsBuffer = gl.createBuffer();
  4934. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  4935. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  4936. gl.enableVertexAttribArray(cache.colorLocation);
  4937. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  4938. 0, 0);
  4939. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  4940. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  4941. gl.drawArrays(gl.TRIANGLES, 0, count);
  4942. gl.flush();
  4943. gl.deleteBuffer(coordsBuffer);
  4944. gl.deleteBuffer(colorsBuffer);
  4945. return canvas;
  4946. }
  4947. function cleanup() {
  4948. smaskCache = null;
  4949. figuresCache = null;
  4950. }
  4951. return {
  4952. get isEnabled() {
  4953. if (PDFJS.disableWebGL) {
  4954. return false;
  4955. }
  4956. var enabled = false;
  4957. try {
  4958. generageGL();
  4959. enabled = !!currentGL;
  4960. } catch (e) { }
  4961. return shadow(this, 'isEnabled', enabled);
  4962. },
  4963. composeSMask: composeSMask,
  4964. drawFigures: drawFigures,
  4965. clear: cleanup
  4966. };
  4967. })();
  4968. var ShadingIRs = {};
  4969. ShadingIRs.RadialAxial = {
  4970. fromIR: function RadialAxial_fromIR(raw) {
  4971. var type = raw[1];
  4972. var colorStops = raw[2];
  4973. var p0 = raw[3];
  4974. var p1 = raw[4];
  4975. var r0 = raw[5];
  4976. var r1 = raw[6];
  4977. return {
  4978. type: 'Pattern',
  4979. getPattern: function RadialAxial_getPattern(ctx) {
  4980. var grad;
  4981. if (type === 'axial') {
  4982. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  4983. } else if (type === 'radial') {
  4984. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  4985. }
  4986. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  4987. var c = colorStops[i];
  4988. grad.addColorStop(c[0], c[1]);
  4989. }
  4990. return grad;
  4991. }
  4992. };
  4993. }
  4994. };
  4995. var createMeshCanvas = (function createMeshCanvasClosure() {
  4996. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  4997. // Very basic Gouraud-shaded triangle rasterization algorithm.
  4998. var coords = context.coords, colors = context.colors;
  4999. var bytes = data.data, rowSize = data.width * 4;
  5000. var tmp;
  5001. if (coords[p1 + 1] > coords[p2 + 1]) {
  5002. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5003. }
  5004. if (coords[p2 + 1] > coords[p3 + 1]) {
  5005. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5006. }
  5007. if (coords[p1 + 1] > coords[p2 + 1]) {
  5008. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5009. }
  5010. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5011. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5012. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5013. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5014. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5015. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5016. if (y1 >= y3) {
  5017. return;
  5018. }
  5019. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5020. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5021. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5022. var minY = Math.round(y1), maxY = Math.round(y3);
  5023. var xa, car, cag, cab;
  5024. var xb, cbr, cbg, cbb;
  5025. var k;
  5026. for (var y = minY; y <= maxY; y++) {
  5027. if (y < y2) {
  5028. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5029. xa = x1 - (x1 - x2) * k;
  5030. car = c1r - (c1r - c2r) * k;
  5031. cag = c1g - (c1g - c2g) * k;
  5032. cab = c1b - (c1b - c2b) * k;
  5033. } else {
  5034. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5035. xa = x2 - (x2 - x3) * k;
  5036. car = c2r - (c2r - c3r) * k;
  5037. cag = c2g - (c2g - c3g) * k;
  5038. cab = c2b - (c2b - c3b) * k;
  5039. }
  5040. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5041. xb = x1 - (x1 - x3) * k;
  5042. cbr = c1r - (c1r - c3r) * k;
  5043. cbg = c1g - (c1g - c3g) * k;
  5044. cbb = c1b - (c1b - c3b) * k;
  5045. var x1_ = Math.round(Math.min(xa, xb));
  5046. var x2_ = Math.round(Math.max(xa, xb));
  5047. var j = rowSize * y + x1_ * 4;
  5048. for (var x = x1_; x <= x2_; x++) {
  5049. k = (xa - x) / (xa - xb);
  5050. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5051. bytes[j++] = (car - (car - cbr) * k) | 0;
  5052. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5053. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5054. bytes[j++] = 255;
  5055. }
  5056. }
  5057. }
  5058. function drawFigure(data, figure, context) {
  5059. var ps = figure.coords;
  5060. var cs = figure.colors;
  5061. var i, ii;
  5062. switch (figure.type) {
  5063. case 'lattice':
  5064. var verticesPerRow = figure.verticesPerRow;
  5065. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5066. var cols = verticesPerRow - 1;
  5067. for (i = 0; i < rows; i++) {
  5068. var q = i * verticesPerRow;
  5069. for (var j = 0; j < cols; j++, q++) {
  5070. drawTriangle(data, context,
  5071. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5072. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5073. drawTriangle(data, context,
  5074. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5075. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5076. }
  5077. }
  5078. break;
  5079. case 'triangles':
  5080. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5081. drawTriangle(data, context,
  5082. ps[i], ps[i + 1], ps[i + 2],
  5083. cs[i], cs[i + 1], cs[i + 2]);
  5084. }
  5085. break;
  5086. default:
  5087. error('illigal figure');
  5088. break;
  5089. }
  5090. }
  5091. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5092. backgroundColor) {
  5093. // we will increase scale on some weird factor to let antialiasing take
  5094. // care of "rough" edges
  5095. var EXPECTED_SCALE = 1.1;
  5096. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5097. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5098. var offsetX = Math.floor(bounds[0]);
  5099. var offsetY = Math.floor(bounds[1]);
  5100. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5101. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5102. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5103. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5104. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5105. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5106. var scaleX = boundsWidth / width;
  5107. var scaleY = boundsHeight / height;
  5108. var context = {
  5109. coords: coords,
  5110. colors: colors,
  5111. offsetX: -offsetX,
  5112. offsetY: -offsetY,
  5113. scaleX: 1 / scaleX,
  5114. scaleY: 1 / scaleY
  5115. };
  5116. var canvas, tmpCanvas, i, ii;
  5117. if (WebGLUtils.isEnabled) {
  5118. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5119. figures, context);
  5120. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5121. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5122. tmpCanvas.context.drawImage(canvas, 0, 0);
  5123. canvas = tmpCanvas.canvas;
  5124. } else {
  5125. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5126. var tmpCtx = tmpCanvas.context;
  5127. var data = tmpCtx.createImageData(width, height);
  5128. if (backgroundColor) {
  5129. var bytes = data.data;
  5130. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5131. bytes[i] = backgroundColor[0];
  5132. bytes[i + 1] = backgroundColor[1];
  5133. bytes[i + 2] = backgroundColor[2];
  5134. bytes[i + 3] = 255;
  5135. }
  5136. }
  5137. for (i = 0; i < figures.length; i++) {
  5138. drawFigure(data, figures[i], context);
  5139. }
  5140. tmpCtx.putImageData(data, 0, 0);
  5141. canvas = tmpCanvas.canvas;
  5142. }
  5143. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5144. scaleX: scaleX, scaleY: scaleY};
  5145. }
  5146. return createMeshCanvas;
  5147. })();
  5148. ShadingIRs.Mesh = {
  5149. fromIR: function Mesh_fromIR(raw) {
  5150. //var type = raw[1];
  5151. var coords = raw[2];
  5152. var colors = raw[3];
  5153. var figures = raw[4];
  5154. var bounds = raw[5];
  5155. var matrix = raw[6];
  5156. //var bbox = raw[7];
  5157. var background = raw[8];
  5158. return {
  5159. type: 'Pattern',
  5160. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5161. var combinedScale;
  5162. // Obtain scale from matrix and current transformation matrix.
  5163. if (shadingFill) {
  5164. combinedScale = Util.singularValueDecompose2dScale(
  5165. ctx.mozCurrentTransform);
  5166. } else {
  5167. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5168. var curMatrixScale = Util.singularValueDecompose2dScale(
  5169. owner.baseTransform);
  5170. combinedScale = [matrixScale[0] * curMatrixScale[0],
  5171. matrixScale[1] * curMatrixScale[1]];
  5172. }
  5173. // Rasterizing on the main thread since sending/queue large canvases
  5174. // might cause OOM.
  5175. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,
  5176. coords, colors, figures, shadingFill ? null : background);
  5177. if (!shadingFill) {
  5178. ctx.setTransform.apply(ctx, owner.baseTransform);
  5179. if (matrix) {
  5180. ctx.transform.apply(ctx, matrix);
  5181. }
  5182. }
  5183. ctx.translate(temporaryPatternCanvas.offsetX,
  5184. temporaryPatternCanvas.offsetY);
  5185. ctx.scale(temporaryPatternCanvas.scaleX,
  5186. temporaryPatternCanvas.scaleY);
  5187. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5188. }
  5189. };
  5190. }
  5191. };
  5192. ShadingIRs.Dummy = {
  5193. fromIR: function Dummy_fromIR() {
  5194. return {
  5195. type: 'Pattern',
  5196. getPattern: function Dummy_fromIR_getPattern() {
  5197. return 'hotpink';
  5198. }
  5199. };
  5200. }
  5201. };
  5202. function getShadingPatternFromIR(raw) {
  5203. var shadingIR = ShadingIRs[raw[0]];
  5204. if (!shadingIR) {
  5205. error('Unknown IR type: ' + raw[0]);
  5206. }
  5207. return shadingIR.fromIR(raw);
  5208. }
  5209. var TilingPattern = (function TilingPatternClosure() {
  5210. var PaintType = {
  5211. COLORED: 1,
  5212. UNCOLORED: 2
  5213. };
  5214. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5215. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5216. this.operatorList = IR[2];
  5217. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5218. this.bbox = IR[4];
  5219. this.xstep = IR[5];
  5220. this.ystep = IR[6];
  5221. this.paintType = IR[7];
  5222. this.tilingType = IR[8];
  5223. this.color = color;
  5224. this.objs = objs;
  5225. this.commonObjs = commonObjs;
  5226. this.baseTransform = baseTransform;
  5227. this.type = 'Pattern';
  5228. this.ctx = ctx;
  5229. }
  5230. TilingPattern.prototype = {
  5231. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5232. var operatorList = this.operatorList;
  5233. var bbox = this.bbox;
  5234. var xstep = this.xstep;
  5235. var ystep = this.ystep;
  5236. var paintType = this.paintType;
  5237. var tilingType = this.tilingType;
  5238. var color = this.color;
  5239. var objs = this.objs;
  5240. var commonObjs = this.commonObjs;
  5241. info('TilingType: ' + tilingType);
  5242. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5243. var topLeft = [x0, y0];
  5244. // we want the canvas to be as large as the step size
  5245. var botRight = [x0 + xstep, y0 + ystep];
  5246. var width = botRight[0] - topLeft[0];
  5247. var height = botRight[1] - topLeft[1];
  5248. // Obtain scale from matrix and current transformation matrix.
  5249. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5250. var curMatrixScale = Util.singularValueDecompose2dScale(
  5251. this.baseTransform);
  5252. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5253. matrixScale[1] * curMatrixScale[1]];
  5254. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5255. // Use width and height values that are as close as possible to the end
  5256. // result when the pattern is used. Too low value makes the pattern look
  5257. // blurry. Too large value makes it look too crispy.
  5258. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5259. MAX_PATTERN_SIZE);
  5260. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5261. MAX_PATTERN_SIZE);
  5262. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5263. var tmpCtx = tmpCanvas.context;
  5264. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5265. graphics.groupLevel = owner.groupLevel;
  5266. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5267. this.setScale(width, height, xstep, ystep);
  5268. this.transformToScale(graphics);
  5269. // transform coordinates to pattern space
  5270. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5271. graphics.transform.apply(graphics, tmpTranslate);
  5272. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5273. graphics.executeOperatorList(operatorList);
  5274. return tmpCanvas.canvas;
  5275. },
  5276. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5277. this.scale = [width / xstep, height / ystep];
  5278. },
  5279. transformToScale: function TilingPattern_transformToScale(graphics) {
  5280. var scale = this.scale;
  5281. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5282. graphics.transform.apply(graphics, tmpScale);
  5283. },
  5284. scaleToContext: function TilingPattern_scaleToContext() {
  5285. var scale = this.scale;
  5286. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5287. },
  5288. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5289. if (bbox && isArray(bbox) && 4 == bbox.length) {
  5290. var bboxWidth = x1 - x0;
  5291. var bboxHeight = y1 - y0;
  5292. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5293. graphics.clip();
  5294. graphics.endPath();
  5295. }
  5296. },
  5297. setFillAndStrokeStyleToContext:
  5298. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5299. switch (paintType) {
  5300. case PaintType.COLORED:
  5301. var ctx = this.ctx;
  5302. context.fillStyle = ctx.fillStyle;
  5303. context.strokeStyle = ctx.strokeStyle;
  5304. break;
  5305. case PaintType.UNCOLORED:
  5306. var cssColor = Util.makeCssRgb(color);
  5307. context.fillStyle = cssColor;
  5308. context.strokeStyle = cssColor;
  5309. break;
  5310. default:
  5311. error('Unsupported paint type: ' + paintType);
  5312. }
  5313. },
  5314. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5315. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5316. ctx = this.ctx;
  5317. ctx.setTransform.apply(ctx, this.baseTransform);
  5318. ctx.transform.apply(ctx, this.matrix);
  5319. this.scaleToContext();
  5320. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5321. }
  5322. };
  5323. return TilingPattern;
  5324. })();
  5325. PDFJS.disableFontFace = false;
  5326. var FontLoader = {
  5327. insertRule: function fontLoaderInsertRule(rule) {
  5328. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5329. if (!styleElement) {
  5330. styleElement = document.createElement('style');
  5331. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5332. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5333. styleElement);
  5334. }
  5335. var styleSheet = styleElement.sheet;
  5336. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5337. },
  5338. clear: function fontLoaderClear() {
  5339. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5340. if (styleElement) {
  5341. styleElement.parentNode.removeChild(styleElement);
  5342. }
  5343. },
  5344. get loadTestFont() {
  5345. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5346. // height.
  5347. return shadow(this, 'loadTestFont', atob(
  5348. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5349. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5350. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5351. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5352. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5353. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5354. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5355. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5356. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5357. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5358. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5359. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5360. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5361. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5362. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5363. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5364. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5365. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5366. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5367. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5368. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5369. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5370. ));
  5371. },
  5372. loadTestFontId: 0,
  5373. loadingContext: {
  5374. requests: [],
  5375. nextRequestId: 0
  5376. },
  5377. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5378. if (isWorker) {
  5379. return false;
  5380. }
  5381. // User agent string sniffing is bad, but there is no reliable way to tell
  5382. // if font is fully loaded and ready to be used with canvas.
  5383. var userAgent = window.navigator.userAgent;
  5384. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5385. if (m && m[1] >= 14) {
  5386. return true;
  5387. }
  5388. // TODO other browsers
  5389. return false;
  5390. })(),
  5391. bind: function fontLoaderBind(fonts, callback) {
  5392. assert(!isWorker, 'bind() shall be called from main thread');
  5393. var rules = [], fontsToLoad = [];
  5394. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5395. var font = fonts[i];
  5396. // Add the font to the DOM only once or skip if the font
  5397. // is already loaded.
  5398. if (font.attached || font.loading === false) {
  5399. continue;
  5400. }
  5401. font.attached = true;
  5402. var rule = font.bindDOM();
  5403. if (rule) {
  5404. rules.push(rule);
  5405. fontsToLoad.push(font);
  5406. }
  5407. }
  5408. var request = FontLoader.queueLoadingCallback(callback);
  5409. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5410. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5411. } else {
  5412. request.complete();
  5413. }
  5414. },
  5415. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5416. function LoadLoader_completeRequest() {
  5417. assert(!request.end, 'completeRequest() cannot be called twice');
  5418. request.end = Date.now();
  5419. // sending all completed requests in order how they were queued
  5420. while (context.requests.length > 0 && context.requests[0].end) {
  5421. var otherRequest = context.requests.shift();
  5422. setTimeout(otherRequest.callback, 0);
  5423. }
  5424. }
  5425. var context = FontLoader.loadingContext;
  5426. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5427. var request = {
  5428. id: requestId,
  5429. complete: LoadLoader_completeRequest,
  5430. callback: callback,
  5431. started: Date.now()
  5432. };
  5433. context.requests.push(request);
  5434. return request;
  5435. },
  5436. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5437. fonts,
  5438. request) {
  5439. /** Hack begin */
  5440. // There's currently no event when a font has finished downloading so the
  5441. // following code is a dirty hack to 'guess' when a font is
  5442. // ready. It's assumed fonts are loaded in order, so add a known test
  5443. // font after the desired fonts and then test for the loading of that
  5444. // test font.
  5445. function int32(data, offset) {
  5446. return (data.charCodeAt(offset) << 24) |
  5447. (data.charCodeAt(offset + 1) << 16) |
  5448. (data.charCodeAt(offset + 2) << 8) |
  5449. (data.charCodeAt(offset + 3) & 0xff);
  5450. }
  5451. function spliceString(s, offset, remove, insert) {
  5452. var chunk1 = s.substr(0, offset);
  5453. var chunk2 = s.substr(offset + remove);
  5454. return chunk1 + insert + chunk2;
  5455. }
  5456. var i, ii;
  5457. var canvas = document.createElement('canvas');
  5458. canvas.width = 1;
  5459. canvas.height = 1;
  5460. var ctx = canvas.getContext('2d');
  5461. var called = 0;
  5462. function isFontReady(name, callback) {
  5463. called++;
  5464. // With setTimeout clamping this gives the font ~100ms to load.
  5465. if(called > 30) {
  5466. warn('Load test font never loaded.');
  5467. callback();
  5468. return;
  5469. }
  5470. ctx.font = '30px ' + name;
  5471. ctx.fillText('.', 0, 20);
  5472. var imageData = ctx.getImageData(0, 0, 1, 1);
  5473. if (imageData.data[3] > 0) {
  5474. callback();
  5475. return;
  5476. }
  5477. setTimeout(isFontReady.bind(null, name, callback));
  5478. }
  5479. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5480. // Chromium seems to cache fonts based on a hash of the actual font data,
  5481. // so the font must be modified for each load test else it will appear to
  5482. // be loaded already.
  5483. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5484. // font by splitting it in chunks before hand and padding the font id.
  5485. var data = this.loadTestFont;
  5486. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5487. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5488. loadTestFontId);
  5489. // CFF checksum is important for IE, adjusting it
  5490. var CFF_CHECKSUM_OFFSET = 16;
  5491. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5492. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5493. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5494. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5495. }
  5496. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5497. checksum = (checksum - XXXX_VALUE +
  5498. int32(loadTestFontId + 'XXX', i)) | 0;
  5499. }
  5500. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5501. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5502. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5503. url + '}';
  5504. FontLoader.insertRule(rule);
  5505. var names = [];
  5506. for (i = 0, ii = fonts.length; i < ii; i++) {
  5507. names.push(fonts[i].loadedName);
  5508. }
  5509. names.push(loadTestFontId);
  5510. var div = document.createElement('div');
  5511. div.setAttribute('style',
  5512. 'visibility: hidden;' +
  5513. 'width: 10px; height: 10px;' +
  5514. 'position: absolute; top: 0px; left: 0px;');
  5515. for (i = 0, ii = names.length; i < ii; ++i) {
  5516. var span = document.createElement('span');
  5517. span.textContent = 'Hi';
  5518. span.style.fontFamily = names[i];
  5519. div.appendChild(span);
  5520. }
  5521. document.body.appendChild(div);
  5522. isFontReady(loadTestFontId, function() {
  5523. document.body.removeChild(div);
  5524. request.complete();
  5525. });
  5526. /** Hack end */
  5527. }
  5528. };
  5529. var FontFace = (function FontFaceClosure() {
  5530. function FontFace(name, file, properties) {
  5531. this.compiledGlyphs = {};
  5532. if (arguments.length === 1) {
  5533. // importing translated data
  5534. var data = arguments[0];
  5535. for (var i in data) {
  5536. this[i] = data[i];
  5537. }
  5538. return;
  5539. }
  5540. }
  5541. FontFace.prototype = {
  5542. bindDOM: function FontFace_bindDOM() {
  5543. if (!this.data) {
  5544. return null;
  5545. }
  5546. if (PDFJS.disableFontFace) {
  5547. this.disableFontFace = true;
  5548. return null;
  5549. }
  5550. var data = bytesToString(new Uint8Array(this.data));
  5551. var fontName = this.loadedName;
  5552. // Add the font-face rule to the document
  5553. var url = ('url(data:' + this.mimetype + ';base64,' +
  5554. window.btoa(data) + ');');
  5555. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5556. FontLoader.insertRule(rule);
  5557. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5558. globalScope['FontInspector'].enabled) {
  5559. globalScope['FontInspector'].fontAdded(this, url);
  5560. }
  5561. return rule;
  5562. },
  5563. getPathGenerator: function (objs, character) {
  5564. if (!(character in this.compiledGlyphs)) {
  5565. var js = objs.get(this.loadedName + '_path_' + character);
  5566. /*jshint -W054 */
  5567. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5568. }
  5569. return this.compiledGlyphs[character];
  5570. }
  5571. };
  5572. return FontFace;
  5573. })();
  5574. var HIGHLIGHT_OFFSET = 4; // px
  5575. var ANNOT_MIN_SIZE = 10; // px
  5576. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5577. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5578. function setTextStyles(element, item, fontObj) {
  5579. var style = element.style;
  5580. style.fontSize = item.fontSize + 'px';
  5581. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5582. if (!fontObj) {
  5583. return;
  5584. }
  5585. style.fontWeight = fontObj.black ?
  5586. (fontObj.bold ? 'bolder' : 'bold') :
  5587. (fontObj.bold ? 'bold' : 'normal');
  5588. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5589. var fontName = fontObj.loadedName;
  5590. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5591. // Use a reasonable default font if the font doesn't specify a fallback
  5592. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5593. style.fontFamily = fontFamily + fallbackName;
  5594. }
  5595. // TODO(mack): Remove this, it's not really that helpful.
  5596. function getEmptyContainer(tagName, rect, borderWidth) {
  5597. var bWidth = borderWidth || 0;
  5598. var element = document.createElement(tagName);
  5599. element.style.borderWidth = bWidth + 'px';
  5600. var width = rect[2] - rect[0] - 2 * bWidth;
  5601. var height = rect[3] - rect[1] - 2 * bWidth;
  5602. element.style.width = width + 'px';
  5603. element.style.height = height + 'px';
  5604. return element;
  5605. }
  5606. function initContainer(item) {
  5607. var container = getEmptyContainer('section', item.rect, item.borderWidth);
  5608. container.style.backgroundColor = item.color;
  5609. var color = item.color;
  5610. var rgb = [];
  5611. for (var i = 0; i < 3; ++i) {
  5612. rgb[i] = Math.round(color[i] * 255);
  5613. }
  5614. item.colorCssRgb = Util.makeCssRgb(rgb);
  5615. var highlight = document.createElement('div');
  5616. highlight.className = 'annotationHighlight';
  5617. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  5618. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  5619. highlight.setAttribute('hidden', true);
  5620. item.highlightElement = highlight;
  5621. container.appendChild(item.highlightElement);
  5622. return container;
  5623. }
  5624. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5625. var element = getEmptyContainer('div', item.rect, 0);
  5626. element.style.display = 'table';
  5627. var content = document.createElement('div');
  5628. content.textContent = item.fieldValue;
  5629. var textAlignment = item.textAlignment;
  5630. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5631. content.style.verticalAlign = 'middle';
  5632. content.style.display = 'table-cell';
  5633. var fontObj = item.fontRefName ?
  5634. commonObjs.getData(item.fontRefName) : null;
  5635. setTextStyles(content, item, fontObj);
  5636. element.appendChild(content);
  5637. return element;
  5638. }
  5639. function getHtmlElementForTextAnnotation(item, commonObjs) {
  5640. var rect = item.rect;
  5641. // sanity check because of OOo-generated PDFs
  5642. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5643. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5644. }
  5645. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5646. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5647. }
  5648. var container = initContainer(item);
  5649. container.className = 'annotText';
  5650. var image = document.createElement('img');
  5651. image.style.height = container.style.height;
  5652. image.style.width = container.style.width;
  5653. var iconName = item.name;
  5654. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5655. iconName.toLowerCase() + '.svg';
  5656. image.alt = '[{{type}} Annotation]';
  5657. image.dataset.l10nId = 'text_annotation_type';
  5658. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5659. var contentWrapper = document.createElement('div');
  5660. contentWrapper.className = 'annotTextContentWrapper';
  5661. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5662. contentWrapper.style.top = '-10px';
  5663. var content = document.createElement('div');
  5664. content.className = 'annotTextContent';
  5665. content.setAttribute('hidden', true);
  5666. var i, ii;
  5667. if (item.hasBgColor) {
  5668. var color = item.color;
  5669. var rgb = [];
  5670. for (i = 0; i < 3; ++i) {
  5671. // Enlighten the color (70%)
  5672. var c = Math.round(color[i] * 255);
  5673. rgb[i] = Math.round((255 - c) * 0.7) + c;
  5674. }
  5675. content.style.backgroundColor = Util.makeCssRgb(rgb);
  5676. }
  5677. var title = document.createElement('h1');
  5678. var text = document.createElement('p');
  5679. title.textContent = item.title;
  5680. if (!item.content && !item.title) {
  5681. content.setAttribute('hidden', true);
  5682. } else {
  5683. var e = document.createElement('span');
  5684. var lines = item.content.split(/(?:\r\n?|\n)/);
  5685. for (i = 0, ii = lines.length; i < ii; ++i) {
  5686. var line = lines[i];
  5687. e.appendChild(document.createTextNode(line));
  5688. if (i < (ii - 1)) {
  5689. e.appendChild(document.createElement('br'));
  5690. }
  5691. }
  5692. text.appendChild(e);
  5693. var pinned = false;
  5694. var showAnnotation = function showAnnotation(pin) {
  5695. if (pin) {
  5696. pinned = true;
  5697. }
  5698. if (content.hasAttribute('hidden')) {
  5699. container.style.zIndex += 1;
  5700. content.removeAttribute('hidden');
  5701. }
  5702. };
  5703. var hideAnnotation = function hideAnnotation(unpin) {
  5704. if (unpin) {
  5705. pinned = false;
  5706. }
  5707. if (!content.hasAttribute('hidden') && !pinned) {
  5708. container.style.zIndex -= 1;
  5709. content.setAttribute('hidden', true);
  5710. }
  5711. };
  5712. var toggleAnnotation = function toggleAnnotation() {
  5713. if (pinned) {
  5714. hideAnnotation(true);
  5715. } else {
  5716. showAnnotation(true);
  5717. }
  5718. };
  5719. image.addEventListener('click', function image_clickHandler() {
  5720. toggleAnnotation();
  5721. }, false);
  5722. image.addEventListener('mouseover', function image_mouseOverHandler() {
  5723. showAnnotation();
  5724. }, false);
  5725. image.addEventListener('mouseout', function image_mouseOutHandler() {
  5726. hideAnnotation();
  5727. }, false);
  5728. content.addEventListener('click', function content_clickHandler() {
  5729. hideAnnotation(true);
  5730. }, false);
  5731. }
  5732. content.appendChild(title);
  5733. content.appendChild(text);
  5734. contentWrapper.appendChild(content);
  5735. container.appendChild(image);
  5736. container.appendChild(contentWrapper);
  5737. return container;
  5738. }
  5739. function getHtmlElementForLinkAnnotation(item, commonObjs) {
  5740. var container = initContainer(item);
  5741. container.className = 'annotLink';
  5742. container.style.borderColor = item.colorCssRgb;
  5743. container.style.borderStyle = 'solid';
  5744. var link = document.createElement('a');
  5745. link.href = link.title = item.url || '';
  5746. container.appendChild(link);
  5747. return container;
  5748. }
  5749. function getHtmlElement(data, objs) {
  5750. switch (data.annotationType) {
  5751. case AnnotationType.WIDGET:
  5752. return getHtmlElementForTextWidgetAnnotation(data, objs);
  5753. case AnnotationType.TEXT:
  5754. return getHtmlElementForTextAnnotation(data, objs);
  5755. case AnnotationType.LINK:
  5756. return getHtmlElementForLinkAnnotation(data, objs);
  5757. default:
  5758. throw new Error('Unsupported annotationType: ' + data.annotationType);
  5759. }
  5760. }
  5761. return {
  5762. getHtmlElement: getHtmlElement
  5763. };
  5764. })();
  5765. PDFJS.AnnotationUtils = AnnotationUtils;
  5766. }).call((typeof window === 'undefined') ? this : window);
  5767. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  5768. // workerSrc is not set -- using last script url to define default location
  5769. PDFJS.workerSrc = (function () {
  5770. 'use strict';
  5771. var scriptTagContainer = document.body ||
  5772. document.getElementsByTagName('head')[0];
  5773. var pdfjsSrc = scriptTagContainer.lastChild.src;
  5774. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  5775. })();
  5776. }