pdf.js 221 KB

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