pdf.js 206 KB

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