pdf.js 220 KB

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