2
0

pdf.js 219 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940
  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.320';
  23. PDFJS.build = 'b2d8e73';
  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 nessessary
  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.rect); // rectangle is nessessary
  1553. },
  1554. loadResources: function Annotation_loadResources(keys) {
  1555. return new Promise(function (resolve, reject) {
  1556. this.appearance.dict.getAsync('Resources').then(function (resources) {
  1557. if (!resources) {
  1558. resolve();
  1559. return;
  1560. }
  1561. var objectLoader = new ObjectLoader(resources.map,
  1562. keys,
  1563. resources.xref);
  1564. objectLoader.load().then(function() {
  1565. resolve(resources);
  1566. }, reject);
  1567. }, reject);
  1568. }.bind(this));
  1569. },
  1570. getOperatorList: function Annotation_getOperatorList(evaluator) {
  1571. if (!this.appearance) {
  1572. return Promise.resolve(new OperatorList());
  1573. }
  1574. var data = this.data;
  1575. var appearanceDict = this.appearance.dict;
  1576. var resourcesPromise = this.loadResources([
  1577. 'ExtGState',
  1578. 'ColorSpace',
  1579. 'Pattern',
  1580. 'Shading',
  1581. 'XObject',
  1582. 'Font'
  1583. // ProcSet
  1584. // Properties
  1585. ]);
  1586. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  1587. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  1588. var transform = getTransformMatrix(data.rect, bbox, matrix);
  1589. var self = this;
  1590. return resourcesPromise.then(function(resources) {
  1591. var opList = new OperatorList();
  1592. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  1593. return evaluator.getOperatorList(self.appearance, resources, opList).
  1594. then(function () {
  1595. opList.addOp(OPS.endAnnotation, []);
  1596. self.appearance.reset();
  1597. return opList;
  1598. });
  1599. });
  1600. }
  1601. };
  1602. Annotation.getConstructor =
  1603. function Annotation_getConstructor(subtype, fieldType) {
  1604. if (!subtype) {
  1605. return;
  1606. }
  1607. // TODO(mack): Implement FreeText annotations
  1608. if (subtype === 'Link') {
  1609. return LinkAnnotation;
  1610. } else if (subtype === 'Text') {
  1611. return TextAnnotation;
  1612. } else if (subtype === 'Widget') {
  1613. if (!fieldType) {
  1614. return;
  1615. }
  1616. if (fieldType === 'Tx') {
  1617. return TextWidgetAnnotation;
  1618. } else {
  1619. return WidgetAnnotation;
  1620. }
  1621. } else {
  1622. return Annotation;
  1623. }
  1624. };
  1625. // TODO(mack): Support loading annotation from data
  1626. Annotation.fromData = function Annotation_fromData(data) {
  1627. var subtype = data.subtype;
  1628. var fieldType = data.fieldType;
  1629. var Constructor = Annotation.getConstructor(subtype, fieldType);
  1630. if (Constructor) {
  1631. return new Constructor({ data: data });
  1632. }
  1633. };
  1634. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  1635. var dict = xref.fetchIfRef(ref);
  1636. if (!isDict(dict)) {
  1637. return;
  1638. }
  1639. var subtype = dict.get('Subtype');
  1640. subtype = isName(subtype) ? subtype.name : '';
  1641. if (!subtype) {
  1642. return;
  1643. }
  1644. var fieldType = Util.getInheritableProperty(dict, 'FT');
  1645. fieldType = isName(fieldType) ? fieldType.name : '';
  1646. var Constructor = Annotation.getConstructor(subtype, fieldType);
  1647. if (!Constructor) {
  1648. return;
  1649. }
  1650. var params = {
  1651. dict: dict,
  1652. ref: ref,
  1653. };
  1654. var annotation = new Constructor(params);
  1655. if (annotation.isViewable() || annotation.isPrintable()) {
  1656. return annotation;
  1657. } else {
  1658. warn('unimplemented annotation type: ' + subtype);
  1659. }
  1660. };
  1661. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  1662. annotations, opList, pdfManager, partialEvaluator, intent) {
  1663. function reject(e) {
  1664. annotationsReadyCapability.reject(e);
  1665. }
  1666. var annotationsReadyCapability = createPromiseCapability();
  1667. var annotationPromises = [];
  1668. for (var i = 0, n = annotations.length; i < n; ++i) {
  1669. if (intent === 'display' && annotations[i].isViewable() ||
  1670. intent === 'print' && annotations[i].isPrintable()) {
  1671. annotationPromises.push(
  1672. annotations[i].getOperatorList(partialEvaluator));
  1673. }
  1674. }
  1675. Promise.all(annotationPromises).then(function(datas) {
  1676. opList.addOp(OPS.beginAnnotations, []);
  1677. for (var i = 0, n = datas.length; i < n; ++i) {
  1678. var annotOpList = datas[i];
  1679. opList.addOpList(annotOpList);
  1680. }
  1681. opList.addOp(OPS.endAnnotations, []);
  1682. annotationsReadyCapability.resolve();
  1683. }, reject);
  1684. return annotationsReadyCapability.promise;
  1685. };
  1686. return Annotation;
  1687. })();
  1688. PDFJS.Annotation = Annotation;
  1689. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  1690. function WidgetAnnotation(params) {
  1691. Annotation.call(this, params);
  1692. if (params.data) {
  1693. return;
  1694. }
  1695. var dict = params.dict;
  1696. var data = this.data;
  1697. data.fieldValue = stringToPDFString(
  1698. Util.getInheritableProperty(dict, 'V') || '');
  1699. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  1700. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  1701. var fieldType = Util.getInheritableProperty(dict, 'FT');
  1702. data.fieldType = isName(fieldType) ? fieldType.name : '';
  1703. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  1704. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  1705. // Building the full field name by collecting the field and
  1706. // its ancestors 'T' data and joining them using '.'.
  1707. var fieldName = [];
  1708. var namedItem = dict;
  1709. var ref = params.ref;
  1710. while (namedItem) {
  1711. var parent = namedItem.get('Parent');
  1712. var parentRef = namedItem.getRaw('Parent');
  1713. var name = namedItem.get('T');
  1714. if (name) {
  1715. fieldName.unshift(stringToPDFString(name));
  1716. } else {
  1717. // The field name is absent, that means more than one field
  1718. // with the same name may exist. Replacing the empty name
  1719. // with the '`' plus index in the parent's 'Kids' array.
  1720. // This is not in the PDF spec but necessary to id the
  1721. // the input controls.
  1722. var kids = parent.get('Kids');
  1723. var j, jj;
  1724. for (j = 0, jj = kids.length; j < jj; j++) {
  1725. var kidRef = kids[j];
  1726. if (kidRef.num == ref.num && kidRef.gen == ref.gen) {
  1727. break;
  1728. }
  1729. }
  1730. fieldName.unshift('`' + j);
  1731. }
  1732. namedItem = parent;
  1733. ref = parentRef;
  1734. }
  1735. data.fullName = fieldName.join('.');
  1736. }
  1737. var parent = Annotation.prototype;
  1738. Util.inherit(WidgetAnnotation, Annotation, {
  1739. isViewable: function WidgetAnnotation_isViewable() {
  1740. if (this.data.fieldType === 'Sig') {
  1741. warn('unimplemented annotation type: Widget signature');
  1742. return false;
  1743. }
  1744. return parent.isViewable.call(this);
  1745. }
  1746. });
  1747. return WidgetAnnotation;
  1748. })();
  1749. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  1750. function TextWidgetAnnotation(params) {
  1751. WidgetAnnotation.call(this, params);
  1752. if (params.data) {
  1753. return;
  1754. }
  1755. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  1756. }
  1757. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  1758. function setTextStyles(element, item, fontObj) {
  1759. var style = element.style;
  1760. style.fontSize = item.fontSize + 'px';
  1761. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  1762. if (!fontObj) {
  1763. return;
  1764. }
  1765. style.fontWeight = fontObj.black ?
  1766. (fontObj.bold ? 'bolder' : 'bold') :
  1767. (fontObj.bold ? 'bold' : 'normal');
  1768. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  1769. var fontName = fontObj.loadedName;
  1770. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  1771. // Use a reasonable default font if the font doesn't specify a fallback
  1772. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  1773. style.fontFamily = fontFamily + fallbackName;
  1774. }
  1775. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  1776. hasHtml: function TextWidgetAnnotation_hasHtml() {
  1777. return !this.data.hasAppearance && !!this.data.fieldValue;
  1778. },
  1779. getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {
  1780. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  1781. var item = this.data;
  1782. var element = this.getEmptyContainer('div');
  1783. element.style.display = 'table';
  1784. var content = document.createElement('div');
  1785. content.textContent = item.fieldValue;
  1786. var textAlignment = item.textAlignment;
  1787. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  1788. content.style.verticalAlign = 'middle';
  1789. content.style.display = 'table-cell';
  1790. var fontObj = item.fontRefName ?
  1791. commonObjs.getData(item.fontRefName) : null;
  1792. setTextStyles(content, item, fontObj);
  1793. element.appendChild(content);
  1794. return element;
  1795. },
  1796. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  1797. if (this.appearance) {
  1798. return Annotation.prototype.getOperatorList.call(this, evaluator);
  1799. }
  1800. var opList = new OperatorList();
  1801. var data = this.data;
  1802. // Even if there is an appearance stream, ignore it. This is the
  1803. // behaviour used by Adobe Reader.
  1804. if (!data.defaultAppearance) {
  1805. return Promise.resolve(opList);
  1806. }
  1807. var stream = new Stream(stringToBytes(data.defaultAppearance));
  1808. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  1809. then(function () {
  1810. return opList;
  1811. });
  1812. }
  1813. });
  1814. return TextWidgetAnnotation;
  1815. })();
  1816. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  1817. function InteractiveAnnotation(params) {
  1818. Annotation.call(this, params);
  1819. }
  1820. Util.inherit(InteractiveAnnotation, Annotation, {
  1821. hasHtml: function InteractiveAnnotation_hasHtml() {
  1822. return true;
  1823. },
  1824. highlight: function InteractiveAnnotation_highlight() {
  1825. if (this.highlightElement &&
  1826. this.highlightElement.hasAttribute('hidden')) {
  1827. this.highlightElement.removeAttribute('hidden');
  1828. }
  1829. },
  1830. unhighlight: function InteractiveAnnotation_unhighlight() {
  1831. if (this.highlightElement &&
  1832. !this.highlightElement.hasAttribute('hidden')) {
  1833. this.highlightElement.setAttribute('hidden', true);
  1834. }
  1835. },
  1836. initContainer: function InteractiveAnnotation_initContainer() {
  1837. var item = this.data;
  1838. var rect = item.rect;
  1839. var container = this.getEmptyContainer('section', rect, item.borderWidth);
  1840. container.style.backgroundColor = item.color;
  1841. var color = item.color;
  1842. var rgb = [];
  1843. for (var i = 0; i < 3; ++i) {
  1844. rgb[i] = Math.round(color[i] * 255);
  1845. }
  1846. item.colorCssRgb = Util.makeCssRgb(rgb);
  1847. var highlight = document.createElement('div');
  1848. highlight.className = 'annotationHighlight';
  1849. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  1850. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  1851. highlight.setAttribute('hidden', true);
  1852. this.highlightElement = highlight;
  1853. container.appendChild(this.highlightElement);
  1854. return container;
  1855. }
  1856. });
  1857. return InteractiveAnnotation;
  1858. })();
  1859. var TextAnnotation = (function TextAnnotationClosure() {
  1860. function TextAnnotation(params) {
  1861. InteractiveAnnotation.call(this, params);
  1862. if (params.data) {
  1863. return;
  1864. }
  1865. var dict = params.dict;
  1866. var data = this.data;
  1867. var content = dict.get('Contents');
  1868. var title = dict.get('T');
  1869. data.content = stringToPDFString(content || '');
  1870. data.title = stringToPDFString(title || '');
  1871. if (data.hasAppearance) {
  1872. data.name = 'NoIcon';
  1873. } else {
  1874. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  1875. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  1876. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  1877. }
  1878. if (dict.has('C')) {
  1879. data.hasBgColor = true;
  1880. }
  1881. }
  1882. var ANNOT_MIN_SIZE = 10;
  1883. Util.inherit(TextAnnotation, InteractiveAnnotation, {
  1884. getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {
  1885. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  1886. var item = this.data;
  1887. var rect = item.rect;
  1888. // sanity check because of OOo-generated PDFs
  1889. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  1890. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  1891. }
  1892. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  1893. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  1894. }
  1895. var container = this.initContainer();
  1896. container.className = 'annotText';
  1897. var image = document.createElement('img');
  1898. image.style.height = container.style.height;
  1899. image.style.width = container.style.width;
  1900. var iconName = item.name;
  1901. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  1902. iconName.toLowerCase() + '.svg';
  1903. image.alt = '[{{type}} Annotation]';
  1904. image.dataset.l10nId = 'text_annotation_type';
  1905. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  1906. var contentWrapper = document.createElement('div');
  1907. contentWrapper.className = 'annotTextContentWrapper';
  1908. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  1909. contentWrapper.style.top = '-10px';
  1910. var content = document.createElement('div');
  1911. content.className = 'annotTextContent';
  1912. content.setAttribute('hidden', true);
  1913. var i, ii;
  1914. if (item.hasBgColor) {
  1915. var color = item.color;
  1916. var rgb = [];
  1917. for (i = 0; i < 3; ++i) {
  1918. // Enlighten the color (70%)
  1919. var c = Math.round(color[i] * 255);
  1920. rgb[i] = Math.round((255 - c) * 0.7) + c;
  1921. }
  1922. content.style.backgroundColor = Util.makeCssRgb(rgb);
  1923. }
  1924. var title = document.createElement('h1');
  1925. var text = document.createElement('p');
  1926. title.textContent = item.title;
  1927. if (!item.content && !item.title) {
  1928. content.setAttribute('hidden', true);
  1929. } else {
  1930. var e = document.createElement('span');
  1931. var lines = item.content.split(/(?:\r\n?|\n)/);
  1932. for (i = 0, ii = lines.length; i < ii; ++i) {
  1933. var line = lines[i];
  1934. e.appendChild(document.createTextNode(line));
  1935. if (i < (ii - 1)) {
  1936. e.appendChild(document.createElement('br'));
  1937. }
  1938. }
  1939. text.appendChild(e);
  1940. var pinned = false;
  1941. var showAnnotation = function showAnnotation(pin) {
  1942. if (pin) {
  1943. pinned = true;
  1944. }
  1945. if (content.hasAttribute('hidden')) {
  1946. container.style.zIndex += 1;
  1947. content.removeAttribute('hidden');
  1948. }
  1949. };
  1950. var hideAnnotation = function hideAnnotation(unpin) {
  1951. if (unpin) {
  1952. pinned = false;
  1953. }
  1954. if (!content.hasAttribute('hidden') && !pinned) {
  1955. container.style.zIndex -= 1;
  1956. content.setAttribute('hidden', true);
  1957. }
  1958. };
  1959. var toggleAnnotation = function toggleAnnotation() {
  1960. if (pinned) {
  1961. hideAnnotation(true);
  1962. } else {
  1963. showAnnotation(true);
  1964. }
  1965. };
  1966. image.addEventListener('click', function image_clickHandler() {
  1967. toggleAnnotation();
  1968. }, false);
  1969. image.addEventListener('mouseover', function image_mouseOverHandler() {
  1970. showAnnotation();
  1971. }, false);
  1972. image.addEventListener('mouseout', function image_mouseOutHandler() {
  1973. hideAnnotation();
  1974. }, false);
  1975. content.addEventListener('click', function content_clickHandler() {
  1976. hideAnnotation(true);
  1977. }, false);
  1978. }
  1979. content.appendChild(title);
  1980. content.appendChild(text);
  1981. contentWrapper.appendChild(content);
  1982. container.appendChild(image);
  1983. container.appendChild(contentWrapper);
  1984. return container;
  1985. }
  1986. });
  1987. return TextAnnotation;
  1988. })();
  1989. var LinkAnnotation = (function LinkAnnotationClosure() {
  1990. function LinkAnnotation(params) {
  1991. InteractiveAnnotation.call(this, params);
  1992. if (params.data) {
  1993. return;
  1994. }
  1995. var dict = params.dict;
  1996. var data = this.data;
  1997. var action = dict.get('A');
  1998. if (action) {
  1999. var linkType = action.get('S').name;
  2000. if (linkType === 'URI') {
  2001. var url = action.get('URI');
  2002. if (isName(url)) {
  2003. // Some bad PDFs do not put parentheses around relative URLs.
  2004. url = '/' + url.name;
  2005. } else if (url) {
  2006. url = addDefaultProtocolToUrl(url);
  2007. }
  2008. // TODO: pdf spec mentions urls can be relative to a Base
  2009. // entry in the dictionary.
  2010. if (!isValidUrl(url, false)) {
  2011. url = '';
  2012. }
  2013. data.url = url;
  2014. } else if (linkType === 'GoTo') {
  2015. data.dest = action.get('D');
  2016. } else if (linkType === 'GoToR') {
  2017. var urlDict = action.get('F');
  2018. if (isDict(urlDict)) {
  2019. // We assume that the 'url' is a Filspec dictionary
  2020. // and fetch the url without checking any further
  2021. url = urlDict.get('F') || '';
  2022. }
  2023. // TODO: pdf reference says that GoToR
  2024. // can also have 'NewWindow' attribute
  2025. if (!isValidUrl(url, false)) {
  2026. url = '';
  2027. }
  2028. data.url = url;
  2029. data.dest = action.get('D');
  2030. } else if (linkType === 'Named') {
  2031. data.action = action.get('N').name;
  2032. } else {
  2033. warn('unrecognized link type: ' + linkType);
  2034. }
  2035. } else if (dict.has('Dest')) {
  2036. // simple destination link
  2037. var dest = dict.get('Dest');
  2038. data.dest = isName(dest) ? dest.name : dest;
  2039. }
  2040. }
  2041. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  2042. function addDefaultProtocolToUrl(url) {
  2043. if (url && url.indexOf('www.') === 0) {
  2044. return ('http://' + url);
  2045. }
  2046. return url;
  2047. }
  2048. Util.inherit(LinkAnnotation, InteractiveAnnotation, {
  2049. hasOperatorList: function LinkAnnotation_hasOperatorList() {
  2050. return false;
  2051. },
  2052. getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {
  2053. var container = this.initContainer();
  2054. container.className = 'annotLink';
  2055. var item = this.data;
  2056. container.style.borderColor = item.colorCssRgb;
  2057. container.style.borderStyle = 'solid';
  2058. var link = document.createElement('a');
  2059. link.href = link.title = this.data.url || '';
  2060. container.appendChild(link);
  2061. return container;
  2062. }
  2063. });
  2064. return LinkAnnotation;
  2065. })();
  2066. /**
  2067. * The maximum allowed image size in total pixels e.g. width * height. Images
  2068. * above this value will not be drawn. Use -1 for no limit.
  2069. * @var {number}
  2070. */
  2071. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  2072. -1 : PDFJS.maxImageSize);
  2073. /**
  2074. * The url of where the predefined Adobe CMaps are located. Include trailing
  2075. * slash.
  2076. * @var {string}
  2077. */
  2078. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  2079. /**
  2080. * Specifies if CMaps are binary packed.
  2081. * @var {boolean}
  2082. */
  2083. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  2084. /*
  2085. * By default fonts are converted to OpenType fonts and loaded via font face
  2086. * rules. If disabled, the font will be rendered using a built in font renderer
  2087. * that constructs the glyphs with primitive path commands.
  2088. * @var {boolean}
  2089. */
  2090. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  2091. false : PDFJS.disableFontFace);
  2092. /**
  2093. * Path for image resources, mainly for annotation icons. Include trailing
  2094. * slash.
  2095. * @var {string}
  2096. */
  2097. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  2098. '' : PDFJS.imageResourcesPath);
  2099. /**
  2100. * Disable the web worker and run all code on the main thread. This will happen
  2101. * automatically if the browser doesn't support workers or sending typed arrays
  2102. * to workers.
  2103. * @var {boolean}
  2104. */
  2105. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  2106. false : PDFJS.disableWorker);
  2107. /**
  2108. * Path and filename of the worker file. Required when the worker is enabled in
  2109. * development mode. If unspecified in the production build, the worker will be
  2110. * loaded based on the location of the pdf.js file.
  2111. * @var {string}
  2112. */
  2113. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  2114. /**
  2115. * Disable range request loading of PDF files. When enabled and if the server
  2116. * supports partial content requests then the PDF will be fetched in chunks.
  2117. * Enabled (false) by default.
  2118. * @var {boolean}
  2119. */
  2120. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  2121. false : PDFJS.disableRange);
  2122. /**
  2123. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  2124. * will automatically keep fetching more data even if it isn't needed to display
  2125. * the current page. This default behavior can be disabled.
  2126. * @var {boolean}
  2127. */
  2128. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  2129. false : PDFJS.disableAutoFetch);
  2130. /**
  2131. * Enables special hooks for debugging PDF.js.
  2132. * @var {boolean}
  2133. */
  2134. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  2135. /**
  2136. * Enables transfer usage in postMessage for ArrayBuffers.
  2137. * @var {boolean}
  2138. */
  2139. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  2140. true : PDFJS.postMessageTransfers);
  2141. /**
  2142. * Disables URL.createObjectURL usage.
  2143. * @var {boolean}
  2144. */
  2145. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  2146. false : PDFJS.disableCreateObjectURL);
  2147. /**
  2148. * Disables WebGL usage.
  2149. * @var {boolean}
  2150. */
  2151. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  2152. true : PDFJS.disableWebGL);
  2153. /**
  2154. * Enables CSS only zooming.
  2155. * @var {boolean}
  2156. */
  2157. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  2158. false : PDFJS.useOnlyCssZoom);
  2159. /**
  2160. * Controls the logging level.
  2161. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  2162. * - errors
  2163. * - warnings [default]
  2164. * - infos
  2165. * @var {number}
  2166. */
  2167. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  2168. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  2169. /**
  2170. * Document initialization / loading parameters object.
  2171. *
  2172. * @typedef {Object} DocumentInitParameters
  2173. * @property {string} url - The URL of the PDF.
  2174. * @property {TypedArray} data - A typed array with PDF data.
  2175. * @property {Object} httpHeaders - Basic authentication headers.
  2176. * @property {boolean} withCredentials - Indicates whether or not cross-site
  2177. * Access-Control requests should be made using credentials such as cookies
  2178. * or authorization headers. The default is false.
  2179. * @property {string} password - For decrypting password-protected PDFs.
  2180. * @property {TypedArray} initialData - A typed array with the first portion or
  2181. * all of the pdf data. Used by the extension since some data is already
  2182. * loaded before the switch to range requests.
  2183. */
  2184. /**
  2185. * This is the main entry point for loading a PDF and interacting with it.
  2186. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  2187. * is used, which means it must follow the same origin rules that any XHR does
  2188. * e.g. No cross domain requests without CORS.
  2189. *
  2190. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  2191. * where a PDF is located, a typed array (Uint8Array) already populated with
  2192. * data or parameter object.
  2193. *
  2194. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  2195. * to manually serve range requests for data in the PDF. See viewer.js for
  2196. * an example of pdfDataRangeTransport's interface.
  2197. *
  2198. * @param {function} passwordCallback is optional. It is used to request a
  2199. * password if wrong or no password was provided. The callback receives two
  2200. * parameters: function that needs to be called with new password and reason
  2201. * (see {PasswordResponses}).
  2202. *
  2203. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  2204. * object.
  2205. */
  2206. PDFJS.getDocument = function getDocument(source,
  2207. pdfDataRangeTransport,
  2208. passwordCallback,
  2209. progressCallback) {
  2210. var workerInitializedCapability, workerReadyCapability, transport;
  2211. if (typeof source === 'string') {
  2212. source = { url: source };
  2213. } else if (isArrayBuffer(source)) {
  2214. source = { data: source };
  2215. } else if (typeof source !== 'object') {
  2216. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  2217. 'string or a parameter object');
  2218. }
  2219. if (!source.url && !source.data) {
  2220. error('Invalid parameter array, need either .data or .url');
  2221. }
  2222. // copy/use all keys as is except 'url' -- full path is required
  2223. var params = {};
  2224. for (var key in source) {
  2225. if (key === 'url' && typeof window !== 'undefined') {
  2226. params[key] = combineUrl(window.location.href, source[key]);
  2227. continue;
  2228. }
  2229. params[key] = source[key];
  2230. }
  2231. workerInitializedCapability = createPromiseCapability();
  2232. workerReadyCapability = createPromiseCapability();
  2233. transport = new WorkerTransport(workerInitializedCapability,
  2234. workerReadyCapability, pdfDataRangeTransport,
  2235. progressCallback);
  2236. workerInitializedCapability.promise.then(function transportInitialized() {
  2237. transport.passwordCallback = passwordCallback;
  2238. transport.fetchDocument(params);
  2239. });
  2240. return workerReadyCapability.promise;
  2241. };
  2242. /**
  2243. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  2244. * properties that can be read synchronously.
  2245. * @class
  2246. */
  2247. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  2248. function PDFDocumentProxy(pdfInfo, transport) {
  2249. this.pdfInfo = pdfInfo;
  2250. this.transport = transport;
  2251. }
  2252. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  2253. /**
  2254. * @return {number} Total number of pages the PDF contains.
  2255. */
  2256. get numPages() {
  2257. return this.pdfInfo.numPages;
  2258. },
  2259. /**
  2260. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  2261. * unique.
  2262. */
  2263. get fingerprint() {
  2264. return this.pdfInfo.fingerprint;
  2265. },
  2266. /**
  2267. * @param {number} pageNumber The page number to get. The first page is 1.
  2268. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  2269. * object.
  2270. */
  2271. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  2272. return this.transport.getPage(pageNumber);
  2273. },
  2274. /**
  2275. * @param {{num: number, gen: number}} ref The page reference. Must have
  2276. * the 'num' and 'gen' properties.
  2277. * @return {Promise} A promise that is resolved with the page index that is
  2278. * associated with the reference.
  2279. */
  2280. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  2281. return this.transport.getPageIndex(ref);
  2282. },
  2283. /**
  2284. * @return {Promise} A promise that is resolved with a lookup table for
  2285. * mapping named destinations to reference numbers.
  2286. */
  2287. getDestinations: function PDFDocumentProxy_getDestinations() {
  2288. return this.transport.getDestinations();
  2289. },
  2290. /**
  2291. * @return {Promise} A promise that is resolved with a lookup table for
  2292. * mapping named attachments to their content.
  2293. */
  2294. getAttachments: function PDFDocumentProxy_getAttachments() {
  2295. return this.transport.getAttachments();
  2296. },
  2297. /**
  2298. * @return {Promise} A promise that is resolved with an array of all the
  2299. * JavaScript strings in the name tree.
  2300. */
  2301. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  2302. return this.transport.getJavaScript();
  2303. },
  2304. /**
  2305. * @return {Promise} A promise that is resolved with an {Array} that is a
  2306. * tree outline (if it has one) of the PDF. The tree is in the format of:
  2307. * [
  2308. * {
  2309. * title: string,
  2310. * bold: boolean,
  2311. * italic: boolean,
  2312. * color: rgb array,
  2313. * dest: dest obj,
  2314. * items: array of more items like this
  2315. * },
  2316. * ...
  2317. * ].
  2318. */
  2319. getOutline: function PDFDocumentProxy_getOutline() {
  2320. return this.transport.getOutline();
  2321. },
  2322. /**
  2323. * @return {Promise} A promise that is resolved with an {Object} that has
  2324. * info and metadata properties. Info is an {Object} filled with anything
  2325. * available in the information dictionary and similarly metadata is a
  2326. * {Metadata} object with information from the metadata section of the PDF.
  2327. */
  2328. getMetadata: function PDFDocumentProxy_getMetadata() {
  2329. return this.transport.getMetadata();
  2330. },
  2331. /**
  2332. * @return {Promise} A promise that is resolved with a TypedArray that has
  2333. * the raw data from the PDF.
  2334. */
  2335. getData: function PDFDocumentProxy_getData() {
  2336. return this.transport.getData();
  2337. },
  2338. /**
  2339. * @return {Promise} A promise that is resolved when the document's data
  2340. * is loaded. It is resolved with an {Object} that contains the length
  2341. * property that indicates size of the PDF data in bytes.
  2342. */
  2343. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  2344. return this.transport.downloadInfoCapability.promise;
  2345. },
  2346. /**
  2347. * Cleans up resources allocated by the document, e.g. created @font-face.
  2348. */
  2349. cleanup: function PDFDocumentProxy_cleanup() {
  2350. this.transport.startCleanup();
  2351. },
  2352. /**
  2353. * Destroys current document instance and terminates worker.
  2354. */
  2355. destroy: function PDFDocumentProxy_destroy() {
  2356. this.transport.destroy();
  2357. }
  2358. };
  2359. return PDFDocumentProxy;
  2360. })();
  2361. /**
  2362. * Page text content.
  2363. *
  2364. * @typedef {Object} TextContent
  2365. * @property {array} items - array of {@link TextItem}
  2366. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  2367. * name.
  2368. */
  2369. /**
  2370. * Page text content part.
  2371. *
  2372. * @typedef {Object} TextItem
  2373. * @property {string} str - text content.
  2374. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  2375. * @property {array} transform - transformation matrix.
  2376. * @property {number} width - width in device space.
  2377. * @property {number} height - height in device space.
  2378. * @property {string} fontName - font name used by pdf.js for converted font.
  2379. */
  2380. /**
  2381. * Text style.
  2382. *
  2383. * @typedef {Object} TextStyle
  2384. * @property {number} ascent - font ascent.
  2385. * @property {number} descent - font descent.
  2386. * @property {boolean} vertical - text is in vertical mode.
  2387. * @property {string} fontFamily - possible font family
  2388. */
  2389. /**
  2390. * Page render parameters.
  2391. *
  2392. * @typedef {Object} RenderParameters
  2393. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  2394. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  2395. * calling of PDFPage.getViewport method.
  2396. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  2397. * (default value is 'display').
  2398. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  2399. * endLayout and appendImage functions.
  2400. * @property {function} continueCallback - (optional) A function that will be
  2401. * called each time the rendering is paused. To continue
  2402. * rendering call the function that is the first argument
  2403. * to the callback.
  2404. */
  2405. /**
  2406. * Proxy to a PDFPage in the worker thread.
  2407. * @class
  2408. */
  2409. var PDFPageProxy = (function PDFPageProxyClosure() {
  2410. function PDFPageProxy(pageIndex, pageInfo, transport) {
  2411. this.pageIndex = pageIndex;
  2412. this.pageInfo = pageInfo;
  2413. this.transport = transport;
  2414. this.stats = new StatTimer();
  2415. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  2416. this.commonObjs = transport.commonObjs;
  2417. this.objs = new PDFObjects();
  2418. this.cleanupAfterRender = false;
  2419. this.pendingDestroy = false;
  2420. this.intentStates = {};
  2421. }
  2422. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  2423. /**
  2424. * @return {number} Page number of the page. First page is 1.
  2425. */
  2426. get pageNumber() {
  2427. return this.pageIndex + 1;
  2428. },
  2429. /**
  2430. * @return {number} The number of degrees the page is rotated clockwise.
  2431. */
  2432. get rotate() {
  2433. return this.pageInfo.rotate;
  2434. },
  2435. /**
  2436. * @return {Object} The reference that points to this page. It has 'num' and
  2437. * 'gen' properties.
  2438. */
  2439. get ref() {
  2440. return this.pageInfo.ref;
  2441. },
  2442. /**
  2443. * @return {Array} An array of the visible portion of the PDF page in the
  2444. * user space units - [x1, y1, x2, y2].
  2445. */
  2446. get view() {
  2447. return this.pageInfo.view;
  2448. },
  2449. /**
  2450. * @param {number} scale The desired scale of the viewport.
  2451. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  2452. * defaults to the page rotation.
  2453. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  2454. * along with transforms required for rendering.
  2455. */
  2456. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  2457. if (arguments.length < 2) {
  2458. rotate = this.rotate;
  2459. }
  2460. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  2461. },
  2462. /**
  2463. * @return {Promise} A promise that is resolved with an {Array} of the
  2464. * annotation objects.
  2465. */
  2466. getAnnotations: function PDFPageProxy_getAnnotations() {
  2467. if (this.annotationsPromise) {
  2468. return this.annotationsPromise;
  2469. }
  2470. var promise = this.transport.getAnnotations(this.pageIndex);
  2471. this.annotationsPromise = promise;
  2472. return promise;
  2473. },
  2474. /**
  2475. * Begins the process of rendering a page to the desired context.
  2476. * @param {RenderParameters} params Page render parameters.
  2477. * @return {RenderTask} An object that contains the promise, which
  2478. * is resolved when the page finishes rendering.
  2479. */
  2480. render: function PDFPageProxy_render(params) {
  2481. var stats = this.stats;
  2482. stats.time('Overall');
  2483. // If there was a pending destroy cancel it so no cleanup happens during
  2484. // this call to render.
  2485. this.pendingDestroy = false;
  2486. var renderingIntent = ('intent' in params ?
  2487. (params.intent == 'print' ? 'print' : 'display') : 'display');
  2488. if (!this.intentStates[renderingIntent]) {
  2489. this.intentStates[renderingIntent] = {};
  2490. }
  2491. var intentState = this.intentStates[renderingIntent];
  2492. // If there's no displayReadyCapability yet, then the operatorList
  2493. // was never requested before. Make the request and create the promise.
  2494. if (!intentState.displayReadyCapability) {
  2495. intentState.receivingOperatorList = true;
  2496. intentState.displayReadyCapability = createPromiseCapability();
  2497. intentState.operatorList = {
  2498. fnArray: [],
  2499. argsArray: [],
  2500. lastChunk: false
  2501. };
  2502. this.stats.time('Page Request');
  2503. this.transport.messageHandler.send('RenderPageRequest', {
  2504. pageIndex: this.pageNumber - 1,
  2505. intent: renderingIntent
  2506. });
  2507. }
  2508. var internalRenderTask = new InternalRenderTask(complete, params,
  2509. this.objs,
  2510. this.commonObjs,
  2511. intentState.operatorList,
  2512. this.pageNumber);
  2513. if (!intentState.renderTasks) {
  2514. intentState.renderTasks = [];
  2515. }
  2516. intentState.renderTasks.push(internalRenderTask);
  2517. var renderTask = new RenderTask(internalRenderTask);
  2518. var self = this;
  2519. intentState.displayReadyCapability.promise.then(
  2520. function pageDisplayReadyPromise(transparency) {
  2521. if (self.pendingDestroy) {
  2522. complete();
  2523. return;
  2524. }
  2525. stats.time('Rendering');
  2526. internalRenderTask.initalizeGraphics(transparency);
  2527. internalRenderTask.operatorListChanged();
  2528. },
  2529. function pageDisplayReadPromiseError(reason) {
  2530. complete(reason);
  2531. }
  2532. );
  2533. function complete(error) {
  2534. var i = intentState.renderTasks.indexOf(internalRenderTask);
  2535. if (i >= 0) {
  2536. intentState.renderTasks.splice(i, 1);
  2537. }
  2538. if (self.cleanupAfterRender) {
  2539. self.pendingDestroy = true;
  2540. }
  2541. self._tryDestroy();
  2542. if (error) {
  2543. internalRenderTask.capability.reject(error);
  2544. } else {
  2545. internalRenderTask.capability.resolve();
  2546. }
  2547. stats.timeEnd('Rendering');
  2548. stats.timeEnd('Overall');
  2549. }
  2550. return renderTask;
  2551. },
  2552. /**
  2553. * @return {Promise} That is resolved a {@link TextContent}
  2554. * object that represent the page text content.
  2555. */
  2556. getTextContent: function PDFPageProxy_getTextContent() {
  2557. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2558. pageIndex: this.pageNumber - 1
  2559. });
  2560. },
  2561. /**
  2562. * Destroys resources allocated by the page.
  2563. */
  2564. destroy: function PDFPageProxy_destroy() {
  2565. this.pendingDestroy = true;
  2566. this._tryDestroy();
  2567. },
  2568. /**
  2569. * For internal use only. Attempts to clean up if rendering is in a state
  2570. * where that's possible.
  2571. * @ignore
  2572. */
  2573. _tryDestroy: function PDFPageProxy__destroy() {
  2574. if (!this.pendingDestroy ||
  2575. Object.keys(this.intentStates).some(function(intent) {
  2576. var intentState = this.intentStates[intent];
  2577. return (intentState.renderTasks.length !== 0 ||
  2578. intentState.receivingOperatorList);
  2579. }, this)) {
  2580. return;
  2581. }
  2582. Object.keys(this.intentStates).forEach(function(intent) {
  2583. delete this.intentStates[intent];
  2584. }, this);
  2585. this.objs.clear();
  2586. this.annotationsPromise = null;
  2587. this.pendingDestroy = false;
  2588. },
  2589. /**
  2590. * For internal use only.
  2591. * @ignore
  2592. */
  2593. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2594. intent) {
  2595. var intentState = this.intentStates[intent];
  2596. intentState.displayReadyCapability.resolve(transparency);
  2597. },
  2598. /**
  2599. * For internal use only.
  2600. * @ignore
  2601. */
  2602. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2603. intent) {
  2604. var intentState = this.intentStates[intent];
  2605. var i, ii;
  2606. // Add the new chunk to the current operator list.
  2607. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2608. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2609. intentState.operatorList.argsArray.push(
  2610. operatorListChunk.argsArray[i]);
  2611. }
  2612. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2613. // Notify all the rendering tasks there are more operators to be consumed.
  2614. for (i = 0; i < intentState.renderTasks.length; i++) {
  2615. intentState.renderTasks[i].operatorListChanged();
  2616. }
  2617. if (operatorListChunk.lastChunk) {
  2618. intentState.receivingOperatorList = false;
  2619. this._tryDestroy();
  2620. }
  2621. }
  2622. };
  2623. return PDFPageProxy;
  2624. })();
  2625. /**
  2626. * For internal use only.
  2627. * @ignore
  2628. */
  2629. var WorkerTransport = (function WorkerTransportClosure() {
  2630. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  2631. pdfDataRangeTransport, progressCallback) {
  2632. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2633. this.workerReadyCapability = workerReadyCapability;
  2634. this.progressCallback = progressCallback;
  2635. this.commonObjs = new PDFObjects();
  2636. this.pageCache = [];
  2637. this.pagePromises = [];
  2638. this.downloadInfoCapability = createPromiseCapability();
  2639. this.passwordCallback = null;
  2640. // If worker support isn't disabled explicit and the browser has worker
  2641. // support, create a new web worker and test if it/the browser fullfills
  2642. // all requirements to run parts of pdf.js in a web worker.
  2643. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2644. // as it arrives on the worker. Chrome added this with version 15.
  2645. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  2646. var workerSrc = PDFJS.workerSrc;
  2647. if (!workerSrc) {
  2648. error('No PDFJS.workerSrc specified');
  2649. }
  2650. try {
  2651. // Some versions of FF can't create a worker on localhost, see:
  2652. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  2653. var worker = new Worker(workerSrc);
  2654. var messageHandler = new MessageHandler('main', worker);
  2655. this.messageHandler = messageHandler;
  2656. messageHandler.on('test', function transportTest(data) {
  2657. var supportTypedArray = data && data.supportTypedArray;
  2658. if (supportTypedArray) {
  2659. this.worker = worker;
  2660. if (!data.supportTransfers) {
  2661. PDFJS.postMessageTransfers = false;
  2662. }
  2663. this.setupMessageHandler(messageHandler);
  2664. workerInitializedCapability.resolve();
  2665. } else {
  2666. globalScope.PDFJS.disableWorker = true;
  2667. this.loadFakeWorkerFiles().then(function() {
  2668. this.setupFakeWorker();
  2669. workerInitializedCapability.resolve();
  2670. }.bind(this));
  2671. }
  2672. }.bind(this));
  2673. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  2674. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  2675. // typed array. Also, checking if we can use transfers.
  2676. try {
  2677. messageHandler.send('test', testObj, [testObj.buffer]);
  2678. } catch (ex) {
  2679. info('Cannot use postMessage transfers');
  2680. testObj[0] = 0;
  2681. messageHandler.send('test', testObj);
  2682. }
  2683. return;
  2684. } catch (e) {
  2685. info('The worker has been disabled.');
  2686. }
  2687. }
  2688. // Either workers are disabled, not supported or have thrown an exception.
  2689. // Thus, we fallback to a faked worker.
  2690. globalScope.PDFJS.disableWorker = true;
  2691. this.loadFakeWorkerFiles().then(function() {
  2692. this.setupFakeWorker();
  2693. workerInitializedCapability.resolve();
  2694. }.bind(this));
  2695. }
  2696. WorkerTransport.prototype = {
  2697. destroy: function WorkerTransport_destroy() {
  2698. this.pageCache = [];
  2699. this.pagePromises = [];
  2700. var self = this;
  2701. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2702. FontLoader.clear();
  2703. if (self.worker) {
  2704. self.worker.terminate();
  2705. }
  2706. });
  2707. },
  2708. loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() {
  2709. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2710. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2711. // In the developer build load worker_loader which in turn loads all the
  2712. // other files and resolves the promise. In production only the
  2713. // pdf.worker.js file is needed.
  2714. Util.loadScript(PDFJS.workerSrc, function() {
  2715. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2716. });
  2717. }
  2718. return PDFJS.fakeWorkerFilesLoadedCapability.promise;
  2719. },
  2720. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2721. warn('Setting up fake worker.');
  2722. // If we don't use a worker, just post/sendMessage to the main thread.
  2723. var fakeWorker = {
  2724. postMessage: function WorkerTransport_postMessage(obj) {
  2725. fakeWorker.onmessage({data: obj});
  2726. },
  2727. terminate: function WorkerTransport_terminate() {}
  2728. };
  2729. var messageHandler = new MessageHandler('main', fakeWorker);
  2730. this.setupMessageHandler(messageHandler);
  2731. // If the main thread is our worker, setup the handling for the messages
  2732. // the main thread sends to it self.
  2733. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2734. },
  2735. setupMessageHandler:
  2736. function WorkerTransport_setupMessageHandler(messageHandler) {
  2737. this.messageHandler = messageHandler;
  2738. function updatePassword(password) {
  2739. messageHandler.send('UpdatePassword', password);
  2740. }
  2741. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2742. if (pdfDataRangeTransport) {
  2743. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2744. messageHandler.send('OnDataRange', {
  2745. begin: begin,
  2746. chunk: chunk
  2747. });
  2748. });
  2749. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2750. messageHandler.send('OnDataProgress', {
  2751. loaded: loaded
  2752. });
  2753. });
  2754. messageHandler.on('RequestDataRange',
  2755. function transportDataRange(data) {
  2756. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2757. }, this);
  2758. }
  2759. messageHandler.on('GetDoc', function transportDoc(data) {
  2760. var pdfInfo = data.pdfInfo;
  2761. this.numPages = data.pdfInfo.numPages;
  2762. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2763. this.pdfDocument = pdfDocument;
  2764. this.workerReadyCapability.resolve(pdfDocument);
  2765. }, this);
  2766. messageHandler.on('NeedPassword', function transportPassword(data) {
  2767. if (this.passwordCallback) {
  2768. return this.passwordCallback(updatePassword,
  2769. PasswordResponses.NEED_PASSWORD);
  2770. }
  2771. this.workerReadyCapability.reject(data.exception.message,
  2772. data.exception);
  2773. }, this);
  2774. messageHandler.on('IncorrectPassword', function transportBadPass(data) {
  2775. if (this.passwordCallback) {
  2776. return this.passwordCallback(updatePassword,
  2777. PasswordResponses.INCORRECT_PASSWORD);
  2778. }
  2779. this.workerReadyCapability.reject(data.exception.message,
  2780. data.exception);
  2781. }, this);
  2782. messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
  2783. this.workerReadyCapability.reject(data.exception.name, data.exception);
  2784. }, this);
  2785. messageHandler.on('MissingPDF', function transportMissingPDF(data) {
  2786. this.workerReadyCapability.reject(data.exception.message,
  2787. data.exception);
  2788. }, this);
  2789. messageHandler.on('UnknownError', function transportUnknownError(data) {
  2790. this.workerReadyCapability.reject(data.exception.message,
  2791. data.exception);
  2792. }, this);
  2793. messageHandler.on('DataLoaded', function transportPage(data) {
  2794. this.downloadInfoCapability.resolve(data);
  2795. }, this);
  2796. messageHandler.on('StartRenderPage', function transportRender(data) {
  2797. var page = this.pageCache[data.pageIndex];
  2798. page.stats.timeEnd('Page Request');
  2799. page._startRenderPage(data.transparency, data.intent);
  2800. }, this);
  2801. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2802. var page = this.pageCache[data.pageIndex];
  2803. page._renderPageChunk(data.operatorList, data.intent);
  2804. }, this);
  2805. messageHandler.on('commonobj', function transportObj(data) {
  2806. var id = data[0];
  2807. var type = data[1];
  2808. if (this.commonObjs.hasData(id)) {
  2809. return;
  2810. }
  2811. switch (type) {
  2812. case 'Font':
  2813. var exportedData = data[2];
  2814. var font;
  2815. if ('error' in exportedData) {
  2816. var error = exportedData.error;
  2817. warn('Error during font loading: ' + error);
  2818. this.commonObjs.resolve(id, error);
  2819. break;
  2820. } else {
  2821. font = new FontFace(exportedData);
  2822. }
  2823. FontLoader.bind(
  2824. [font],
  2825. function fontReady(fontObjs) {
  2826. this.commonObjs.resolve(id, font);
  2827. }.bind(this)
  2828. );
  2829. break;
  2830. case 'FontPath':
  2831. this.commonObjs.resolve(id, data[2]);
  2832. break;
  2833. default:
  2834. error('Got unknown common object type ' + type);
  2835. }
  2836. }, this);
  2837. messageHandler.on('obj', function transportObj(data) {
  2838. var id = data[0];
  2839. var pageIndex = data[1];
  2840. var type = data[2];
  2841. var pageProxy = this.pageCache[pageIndex];
  2842. var imageData;
  2843. if (pageProxy.objs.hasData(id)) {
  2844. return;
  2845. }
  2846. switch (type) {
  2847. case 'JpegStream':
  2848. imageData = data[3];
  2849. loadJpegStream(id, imageData, pageProxy.objs);
  2850. break;
  2851. case 'Image':
  2852. imageData = data[3];
  2853. pageProxy.objs.resolve(id, imageData);
  2854. // heuristics that will allow not to store large data
  2855. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2856. if (imageData && 'data' in imageData &&
  2857. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2858. pageProxy.cleanupAfterRender = true;
  2859. }
  2860. break;
  2861. default:
  2862. error('Got unknown object type ' + type);
  2863. }
  2864. }, this);
  2865. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2866. if (this.progressCallback) {
  2867. this.progressCallback({
  2868. loaded: data.loaded,
  2869. total: data.total
  2870. });
  2871. }
  2872. }, this);
  2873. messageHandler.on('DocError', function transportDocError(data) {
  2874. this.workerReadyCapability.reject(data);
  2875. }, this);
  2876. messageHandler.on('PageError', function transportError(data) {
  2877. var page = this.pageCache[data.pageNum - 1];
  2878. var intentState = page.intentStates[data.intent];
  2879. if (intentState.displayReadyCapability.promise) {
  2880. intentState.displayReadyCapability.reject(data.error);
  2881. } else {
  2882. error(data.error);
  2883. }
  2884. }, this);
  2885. messageHandler.on('JpegDecode', function(data) {
  2886. var imageUrl = data[0];
  2887. var components = data[1];
  2888. if (components != 3 && components != 1) {
  2889. return Promise.reject(
  2890. new Error('Only 3 components or 1 component can be returned'));
  2891. }
  2892. return new Promise(function (resolve, reject) {
  2893. var img = new Image();
  2894. img.onload = function () {
  2895. var width = img.width;
  2896. var height = img.height;
  2897. var size = width * height;
  2898. var rgbaLength = size * 4;
  2899. var buf = new Uint8Array(size * components);
  2900. var tmpCanvas = createScratchCanvas(width, height);
  2901. var tmpCtx = tmpCanvas.getContext('2d');
  2902. tmpCtx.drawImage(img, 0, 0);
  2903. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2904. var i, j;
  2905. if (components == 3) {
  2906. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2907. buf[j] = data[i];
  2908. buf[j + 1] = data[i + 1];
  2909. buf[j + 2] = data[i + 2];
  2910. }
  2911. } else if (components == 1) {
  2912. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2913. buf[j] = data[i];
  2914. }
  2915. }
  2916. resolve({ data: buf, width: width, height: height});
  2917. };
  2918. img.onerror = function () {
  2919. reject(new Error('JpegDecode failed to load image'));
  2920. };
  2921. img.src = imageUrl;
  2922. });
  2923. });
  2924. },
  2925. fetchDocument: function WorkerTransport_fetchDocument(source) {
  2926. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2927. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2928. this.messageHandler.send('GetDocRequest', {
  2929. source: source,
  2930. disableRange: PDFJS.disableRange,
  2931. maxImageSize: PDFJS.maxImageSize,
  2932. cMapUrl: PDFJS.cMapUrl,
  2933. cMapPacked: PDFJS.cMapPacked,
  2934. disableFontFace: PDFJS.disableFontFace,
  2935. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2936. verbosity: PDFJS.verbosity
  2937. });
  2938. },
  2939. getData: function WorkerTransport_getData() {
  2940. return this.messageHandler.sendWithPromise('GetData', null);
  2941. },
  2942. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2943. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2944. (pageNumber|0) !== pageNumber) {
  2945. return Promise.reject(new Error('Invalid page request'));
  2946. }
  2947. var pageIndex = pageNumber - 1;
  2948. if (pageIndex in this.pagePromises) {
  2949. return this.pagePromises[pageIndex];
  2950. }
  2951. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2952. pageIndex: pageIndex
  2953. }).then(function (pageInfo) {
  2954. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2955. this.pageCache[pageIndex] = page;
  2956. return page;
  2957. }.bind(this));
  2958. this.pagePromises[pageIndex] = promise;
  2959. return promise;
  2960. },
  2961. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2962. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2963. },
  2964. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2965. return this.messageHandler.sendWithPromise('GetAnnotations',
  2966. { pageIndex: pageIndex });
  2967. },
  2968. getDestinations: function WorkerTransport_getDestinations() {
  2969. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2970. },
  2971. getAttachments: function WorkerTransport_getAttachments() {
  2972. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2973. },
  2974. getJavaScript: function WorkerTransport_getJavaScript() {
  2975. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2976. },
  2977. getOutline: function WorkerTransport_getOutline() {
  2978. return this.messageHandler.sendWithPromise('GetOutline', null);
  2979. },
  2980. getMetadata: function WorkerTransport_getMetadata() {
  2981. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2982. then(function transportMetadata(results) {
  2983. return {
  2984. info: results[0],
  2985. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2986. };
  2987. });
  2988. },
  2989. startCleanup: function WorkerTransport_startCleanup() {
  2990. this.messageHandler.sendWithPromise('Cleanup', null).
  2991. then(function endCleanup() {
  2992. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2993. var page = this.pageCache[i];
  2994. if (page) {
  2995. page.destroy();
  2996. }
  2997. }
  2998. this.commonObjs.clear();
  2999. FontLoader.clear();
  3000. }.bind(this));
  3001. }
  3002. };
  3003. return WorkerTransport;
  3004. })();
  3005. /**
  3006. * A PDF document and page is built of many objects. E.g. there are objects
  3007. * for fonts, images, rendering code and such. These objects might get processed
  3008. * inside of a worker. The `PDFObjects` implements some basic functions to
  3009. * manage these objects.
  3010. * @ignore
  3011. */
  3012. var PDFObjects = (function PDFObjectsClosure() {
  3013. function PDFObjects() {
  3014. this.objs = {};
  3015. }
  3016. PDFObjects.prototype = {
  3017. /**
  3018. * Internal function.
  3019. * Ensures there is an object defined for `objId`.
  3020. */
  3021. ensureObj: function PDFObjects_ensureObj(objId) {
  3022. if (this.objs[objId]) {
  3023. return this.objs[objId];
  3024. }
  3025. var obj = {
  3026. capability: createPromiseCapability(),
  3027. data: null,
  3028. resolved: false
  3029. };
  3030. this.objs[objId] = obj;
  3031. return obj;
  3032. },
  3033. /**
  3034. * If called *without* callback, this returns the data of `objId` but the
  3035. * object needs to be resolved. If it isn't, this function throws.
  3036. *
  3037. * If called *with* a callback, the callback is called with the data of the
  3038. * object once the object is resolved. That means, if you call this
  3039. * function and the object is already resolved, the callback gets called
  3040. * right away.
  3041. */
  3042. get: function PDFObjects_get(objId, callback) {
  3043. // If there is a callback, then the get can be async and the object is
  3044. // not required to be resolved right now
  3045. if (callback) {
  3046. this.ensureObj(objId).capability.promise.then(callback);
  3047. return null;
  3048. }
  3049. // If there isn't a callback, the user expects to get the resolved data
  3050. // directly.
  3051. var obj = this.objs[objId];
  3052. // If there isn't an object yet or the object isn't resolved, then the
  3053. // data isn't ready yet!
  3054. if (!obj || !obj.resolved) {
  3055. error('Requesting object that isn\'t resolved yet ' + objId);
  3056. }
  3057. return obj.data;
  3058. },
  3059. /**
  3060. * Resolves the object `objId` with optional `data`.
  3061. */
  3062. resolve: function PDFObjects_resolve(objId, data) {
  3063. var obj = this.ensureObj(objId);
  3064. obj.resolved = true;
  3065. obj.data = data;
  3066. obj.capability.resolve(data);
  3067. },
  3068. isResolved: function PDFObjects_isResolved(objId) {
  3069. var objs = this.objs;
  3070. if (!objs[objId]) {
  3071. return false;
  3072. } else {
  3073. return objs[objId].resolved;
  3074. }
  3075. },
  3076. hasData: function PDFObjects_hasData(objId) {
  3077. return this.isResolved(objId);
  3078. },
  3079. /**
  3080. * Returns the data of `objId` if object exists, null otherwise.
  3081. */
  3082. getData: function PDFObjects_getData(objId) {
  3083. var objs = this.objs;
  3084. if (!objs[objId] || !objs[objId].resolved) {
  3085. return null;
  3086. } else {
  3087. return objs[objId].data;
  3088. }
  3089. },
  3090. clear: function PDFObjects_clear() {
  3091. this.objs = {};
  3092. }
  3093. };
  3094. return PDFObjects;
  3095. })();
  3096. /**
  3097. * Allows controlling of the rendering tasks.
  3098. * @class
  3099. */
  3100. var RenderTask = (function RenderTaskClosure() {
  3101. function RenderTask(internalRenderTask) {
  3102. this.internalRenderTask = internalRenderTask;
  3103. /**
  3104. * Promise for rendering task completion.
  3105. * @type {Promise}
  3106. */
  3107. this.promise = this.internalRenderTask.capability.promise;
  3108. }
  3109. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  3110. /**
  3111. * Cancels the rendering task. If the task is currently rendering it will
  3112. * not be cancelled until graphics pauses with a timeout. The promise that
  3113. * this object extends will resolved when cancelled.
  3114. */
  3115. cancel: function RenderTask_cancel() {
  3116. this.internalRenderTask.cancel();
  3117. },
  3118. /**
  3119. * Registers callback to indicate the rendering task completion.
  3120. *
  3121. * @param {function} onFulfilled The callback for the rendering completion.
  3122. * @param {function} onRejected The callback for the rendering failure.
  3123. * @return {Promise} A promise that is resolved after the onFulfilled or
  3124. * onRejected callback.
  3125. */
  3126. then: function RenderTask_then(onFulfilled, onRejected) {
  3127. return this.promise.then(onFulfilled, onRejected);
  3128. }
  3129. };
  3130. return RenderTask;
  3131. })();
  3132. /**
  3133. * For internal use only.
  3134. * @ignore
  3135. */
  3136. var InternalRenderTask = (function InternalRenderTaskClosure() {
  3137. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  3138. pageNumber) {
  3139. this.callback = callback;
  3140. this.params = params;
  3141. this.objs = objs;
  3142. this.commonObjs = commonObjs;
  3143. this.operatorListIdx = null;
  3144. this.operatorList = operatorList;
  3145. this.pageNumber = pageNumber;
  3146. this.running = false;
  3147. this.graphicsReadyCallback = null;
  3148. this.graphicsReady = false;
  3149. this.cancelled = false;
  3150. this.capability = createPromiseCapability();
  3151. // caching this-bound methods
  3152. this._continueBound = this._continue.bind(this);
  3153. this._scheduleNextBound = this._scheduleNext.bind(this);
  3154. this._nextBound = this._next.bind(this);
  3155. }
  3156. InternalRenderTask.prototype = {
  3157. initalizeGraphics:
  3158. function InternalRenderTask_initalizeGraphics(transparency) {
  3159. if (this.cancelled) {
  3160. return;
  3161. }
  3162. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  3163. globalScope.StepperManager.enabled) {
  3164. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  3165. this.stepper.init(this.operatorList);
  3166. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  3167. }
  3168. var params = this.params;
  3169. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  3170. this.objs, params.imageLayer);
  3171. this.gfx.beginDrawing(params.viewport, transparency);
  3172. this.operatorListIdx = 0;
  3173. this.graphicsReady = true;
  3174. if (this.graphicsReadyCallback) {
  3175. this.graphicsReadyCallback();
  3176. }
  3177. },
  3178. cancel: function InternalRenderTask_cancel() {
  3179. this.running = false;
  3180. this.cancelled = true;
  3181. this.callback('cancelled');
  3182. },
  3183. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  3184. if (!this.graphicsReady) {
  3185. if (!this.graphicsReadyCallback) {
  3186. this.graphicsReadyCallback = this._continueBound;
  3187. }
  3188. return;
  3189. }
  3190. if (this.stepper) {
  3191. this.stepper.updateOperatorList(this.operatorList);
  3192. }
  3193. if (this.running) {
  3194. return;
  3195. }
  3196. this._continue();
  3197. },
  3198. _continue: function InternalRenderTask__continue() {
  3199. this.running = true;
  3200. if (this.cancelled) {
  3201. return;
  3202. }
  3203. if (this.params.continueCallback) {
  3204. this.params.continueCallback(this._scheduleNextBound);
  3205. } else {
  3206. this._scheduleNext();
  3207. }
  3208. },
  3209. _scheduleNext: function InternalRenderTask__scheduleNext() {
  3210. window.requestAnimationFrame(this._nextBound);
  3211. },
  3212. _next: function InternalRenderTask__next() {
  3213. if (this.cancelled) {
  3214. return;
  3215. }
  3216. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  3217. this.operatorListIdx,
  3218. this._continueBound,
  3219. this.stepper);
  3220. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  3221. this.running = false;
  3222. if (this.operatorList.lastChunk) {
  3223. this.gfx.endDrawing();
  3224. this.callback();
  3225. }
  3226. }
  3227. }
  3228. };
  3229. return InternalRenderTask;
  3230. })();
  3231. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  3232. function fixMetadata(meta) {
  3233. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  3234. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  3235. function(code, d1, d2, d3) {
  3236. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  3237. });
  3238. var chars = '';
  3239. for (var i = 0; i < bytes.length; i += 2) {
  3240. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  3241. chars += code >= 32 && code < 127 && code != 60 && code != 62 &&
  3242. code != 38 && false ? String.fromCharCode(code) :
  3243. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  3244. }
  3245. return '>' + chars;
  3246. });
  3247. }
  3248. function Metadata(meta) {
  3249. if (typeof meta === 'string') {
  3250. // Ghostscript produces invalid metadata
  3251. meta = fixMetadata(meta);
  3252. var parser = new DOMParser();
  3253. meta = parser.parseFromString(meta, 'application/xml');
  3254. } else if (!(meta instanceof Document)) {
  3255. error('Metadata: Invalid metadata object');
  3256. }
  3257. this.metaDocument = meta;
  3258. this.metadata = {};
  3259. this.parse();
  3260. }
  3261. Metadata.prototype = {
  3262. parse: function Metadata_parse() {
  3263. var doc = this.metaDocument;
  3264. var rdf = doc.documentElement;
  3265. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  3266. rdf = rdf.firstChild;
  3267. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3268. rdf = rdf.nextSibling;
  3269. }
  3270. }
  3271. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  3272. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3273. return;
  3274. }
  3275. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3276. for (i = 0, length = children.length; i < length; i++) {
  3277. desc = children[i];
  3278. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3279. continue;
  3280. }
  3281. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3282. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3283. entry = desc.childNodes[ii];
  3284. name = entry.nodeName.toLowerCase();
  3285. this.metadata[name] = entry.textContent.trim();
  3286. }
  3287. }
  3288. }
  3289. },
  3290. get: function Metadata_get(name) {
  3291. return this.metadata[name] || null;
  3292. },
  3293. has: function Metadata_has(name) {
  3294. return typeof this.metadata[name] !== 'undefined';
  3295. }
  3296. };
  3297. return Metadata;
  3298. })();
  3299. // <canvas> contexts store most of the state we need natively.
  3300. // However, PDF needs a bit more state, which we store here.
  3301. // Minimal font size that would be used during canvas fillText operations.
  3302. var MIN_FONT_SIZE = 16;
  3303. var MAX_GROUP_SIZE = 4096;
  3304. var COMPILE_TYPE3_GLYPHS = true;
  3305. function createScratchCanvas(width, height) {
  3306. var canvas = document.createElement('canvas');
  3307. canvas.width = width;
  3308. canvas.height = height;
  3309. return canvas;
  3310. }
  3311. function addContextCurrentTransform(ctx) {
  3312. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  3313. if (!ctx.mozCurrentTransform) {
  3314. // Store the original context
  3315. ctx._scaleX = ctx._scaleX || 1.0;
  3316. ctx._scaleY = ctx._scaleY || 1.0;
  3317. ctx._originalSave = ctx.save;
  3318. ctx._originalRestore = ctx.restore;
  3319. ctx._originalRotate = ctx.rotate;
  3320. ctx._originalScale = ctx.scale;
  3321. ctx._originalTranslate = ctx.translate;
  3322. ctx._originalTransform = ctx.transform;
  3323. ctx._originalSetTransform = ctx.setTransform;
  3324. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  3325. ctx._transformStack = [];
  3326. Object.defineProperty(ctx, 'mozCurrentTransform', {
  3327. get: function getCurrentTransform() {
  3328. return this._transformMatrix;
  3329. }
  3330. });
  3331. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  3332. get: function getCurrentTransformInverse() {
  3333. // Calculation done using WolframAlpha:
  3334. // http://www.wolframalpha.com/input/?
  3335. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  3336. var m = this._transformMatrix;
  3337. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  3338. var ad_bc = a * d - b * c;
  3339. var bc_ad = b * c - a * d;
  3340. return [
  3341. d / ad_bc,
  3342. b / bc_ad,
  3343. c / bc_ad,
  3344. a / ad_bc,
  3345. (d * e - c * f) / bc_ad,
  3346. (b * e - a * f) / ad_bc
  3347. ];
  3348. }
  3349. });
  3350. ctx.save = function ctxSave() {
  3351. var old = this._transformMatrix;
  3352. this._transformStack.push(old);
  3353. this._transformMatrix = old.slice(0, 6);
  3354. this._originalSave();
  3355. };
  3356. ctx.restore = function ctxRestore() {
  3357. var prev = this._transformStack.pop();
  3358. if (prev) {
  3359. this._transformMatrix = prev;
  3360. this._originalRestore();
  3361. }
  3362. };
  3363. ctx.translate = function ctxTranslate(x, y) {
  3364. var m = this._transformMatrix;
  3365. m[4] = m[0] * x + m[2] * y + m[4];
  3366. m[5] = m[1] * x + m[3] * y + m[5];
  3367. this._originalTranslate(x, y);
  3368. };
  3369. ctx.scale = function ctxScale(x, y) {
  3370. var m = this._transformMatrix;
  3371. m[0] = m[0] * x;
  3372. m[1] = m[1] * x;
  3373. m[2] = m[2] * y;
  3374. m[3] = m[3] * y;
  3375. this._originalScale(x, y);
  3376. };
  3377. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3378. var m = this._transformMatrix;
  3379. this._transformMatrix = [
  3380. m[0] * a + m[2] * b,
  3381. m[1] * a + m[3] * b,
  3382. m[0] * c + m[2] * d,
  3383. m[1] * c + m[3] * d,
  3384. m[0] * e + m[2] * f + m[4],
  3385. m[1] * e + m[3] * f + m[5]
  3386. ];
  3387. ctx._originalTransform(a, b, c, d, e, f);
  3388. };
  3389. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3390. this._transformMatrix = [a, b, c, d, e, f];
  3391. ctx._originalSetTransform(a, b, c, d, e, f);
  3392. };
  3393. ctx.rotate = function ctxRotate(angle) {
  3394. var cosValue = Math.cos(angle);
  3395. var sinValue = Math.sin(angle);
  3396. var m = this._transformMatrix;
  3397. this._transformMatrix = [
  3398. m[0] * cosValue + m[2] * sinValue,
  3399. m[1] * cosValue + m[3] * sinValue,
  3400. m[0] * (-sinValue) + m[2] * cosValue,
  3401. m[1] * (-sinValue) + m[3] * cosValue,
  3402. m[4],
  3403. m[5]
  3404. ];
  3405. this._originalRotate(angle);
  3406. };
  3407. }
  3408. }
  3409. var CachedCanvases = (function CachedCanvasesClosure() {
  3410. var cache = {};
  3411. return {
  3412. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  3413. trackTransform) {
  3414. var canvasEntry;
  3415. if (id in cache) {
  3416. canvasEntry = cache[id];
  3417. canvasEntry.canvas.width = width;
  3418. canvasEntry.canvas.height = height;
  3419. // reset canvas transform for emulated mozCurrentTransform, if needed
  3420. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3421. } else {
  3422. var canvas = createScratchCanvas(width, height);
  3423. var ctx = canvas.getContext('2d');
  3424. if (trackTransform) {
  3425. addContextCurrentTransform(ctx);
  3426. }
  3427. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  3428. }
  3429. return canvasEntry;
  3430. },
  3431. clear: function () {
  3432. cache = {};
  3433. }
  3434. };
  3435. })();
  3436. function compileType3Glyph(imgData) {
  3437. var POINT_TO_PROCESS_LIMIT = 1000;
  3438. var width = imgData.width, height = imgData.height;
  3439. var i, j, j0, width1 = width + 1;
  3440. var points = new Uint8Array(width1 * (height + 1));
  3441. var POINT_TYPES =
  3442. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3443. // decodes bit-packed mask data
  3444. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  3445. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  3446. for (i = 0, ii = data0.length; i < ii; i++) {
  3447. var mask = 128, elem = data0[i];
  3448. while (mask > 0) {
  3449. data[pos++] = (elem & mask) ? 0 : 255;
  3450. mask >>= 1;
  3451. }
  3452. }
  3453. // finding iteresting points: every point is located between mask pixels,
  3454. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  3455. // will have flags assigned based on neighboring mask pixels:
  3456. // 4 | 8
  3457. // --P--
  3458. // 2 | 1
  3459. // We are interested only in points with the flags:
  3460. // - outside corners: 1, 2, 4, 8;
  3461. // - inside corners: 7, 11, 13, 14;
  3462. // - and, intersections: 5, 10.
  3463. var count = 0;
  3464. pos = 0;
  3465. if (data[pos] !== 0) {
  3466. points[0] = 1;
  3467. ++count;
  3468. }
  3469. for (j = 1; j < width; j++) {
  3470. if (data[pos] !== data[pos + 1]) {
  3471. points[j] = data[pos] ? 2 : 1;
  3472. ++count;
  3473. }
  3474. pos++;
  3475. }
  3476. if (data[pos] !== 0) {
  3477. points[j] = 2;
  3478. ++count;
  3479. }
  3480. for (i = 1; i < height; i++) {
  3481. pos = i * lineSize;
  3482. j0 = i * width1;
  3483. if (data[pos - lineSize] !== data[pos]) {
  3484. points[j0] = data[pos] ? 1 : 8;
  3485. ++count;
  3486. }
  3487. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  3488. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  3489. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3490. for (j = 1; j < width; j++) {
  3491. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  3492. (data[pos - lineSize + 1] ? 8 : 0);
  3493. if (POINT_TYPES[sum]) {
  3494. points[j0 + j] = POINT_TYPES[sum];
  3495. ++count;
  3496. }
  3497. pos++;
  3498. }
  3499. if (data[pos - lineSize] !== data[pos]) {
  3500. points[j0 + j] = data[pos] ? 2 : 4;
  3501. ++count;
  3502. }
  3503. if (count > POINT_TO_PROCESS_LIMIT) {
  3504. return null;
  3505. }
  3506. }
  3507. pos = lineSize * (height - 1);
  3508. j0 = i * width1;
  3509. if (data[pos] !== 0) {
  3510. points[j0] = 8;
  3511. ++count;
  3512. }
  3513. for (j = 1; j < width; j++) {
  3514. if (data[pos] !== data[pos + 1]) {
  3515. points[j0 + j] = data[pos] ? 4 : 8;
  3516. ++count;
  3517. }
  3518. pos++;
  3519. }
  3520. if (data[pos] !== 0) {
  3521. points[j0 + j] = 4;
  3522. ++count;
  3523. }
  3524. if (count > POINT_TO_PROCESS_LIMIT) {
  3525. return null;
  3526. }
  3527. // building outlines
  3528. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3529. var outlines = [];
  3530. for (i = 0; count && i <= height; i++) {
  3531. var p = i * width1;
  3532. var end = p + width;
  3533. while (p < end && !points[p]) {
  3534. p++;
  3535. }
  3536. if (p === end) {
  3537. continue;
  3538. }
  3539. var coords = [p % width1, i];
  3540. var type = points[p], p0 = p, pp;
  3541. do {
  3542. var step = steps[type];
  3543. do {
  3544. p += step;
  3545. } while (!points[p]);
  3546. pp = points[p];
  3547. if (pp !== 5 && pp !== 10) {
  3548. // set new direction
  3549. type = pp;
  3550. // delete mark
  3551. points[p] = 0;
  3552. } else { // type is 5 or 10, ie, a crossing
  3553. // set new direction
  3554. type = pp & ((0x33 * type) >> 4);
  3555. // set new type for "future hit"
  3556. points[p] &= (type >> 2 | type << 2);
  3557. }
  3558. coords.push(p % width1);
  3559. coords.push((p / width1) | 0);
  3560. --count;
  3561. } while (p0 !== p);
  3562. outlines.push(coords);
  3563. --i;
  3564. }
  3565. var drawOutline = function(c) {
  3566. c.save();
  3567. // the path shall be painted in [0..1]x[0..1] space
  3568. c.scale(1 / width, -1 / height);
  3569. c.translate(0, -height);
  3570. c.beginPath();
  3571. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3572. var o = outlines[i];
  3573. c.moveTo(o[0], o[1]);
  3574. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3575. c.lineTo(o[j], o[j+1]);
  3576. }
  3577. }
  3578. c.fill();
  3579. c.beginPath();
  3580. c.restore();
  3581. };
  3582. return drawOutline;
  3583. }
  3584. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3585. function CanvasExtraState(old) {
  3586. // Are soft masks and alpha values shapes or opacities?
  3587. this.alphaIsShape = false;
  3588. this.fontSize = 0;
  3589. this.fontSizeScale = 1;
  3590. this.textMatrix = IDENTITY_MATRIX;
  3591. this.textMatrixScale = 1;
  3592. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3593. this.leading = 0;
  3594. // Current point (in user coordinates)
  3595. this.x = 0;
  3596. this.y = 0;
  3597. // Start of text line (in text coordinates)
  3598. this.lineX = 0;
  3599. this.lineY = 0;
  3600. // Character and word spacing
  3601. this.charSpacing = 0;
  3602. this.wordSpacing = 0;
  3603. this.textHScale = 1;
  3604. this.textRenderingMode = TextRenderingMode.FILL;
  3605. this.textRise = 0;
  3606. // Default fore and background colors
  3607. this.fillColor = '#000000';
  3608. this.strokeColor = '#000000';
  3609. // Note: fill alpha applies to all non-stroking operations
  3610. this.fillAlpha = 1;
  3611. this.strokeAlpha = 1;
  3612. this.lineWidth = 1;
  3613. this.activeSMask = null; // nonclonable field (see the save method below)
  3614. this.old = old;
  3615. }
  3616. CanvasExtraState.prototype = {
  3617. clone: function CanvasExtraState_clone() {
  3618. return Object.create(this);
  3619. },
  3620. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3621. this.x = x;
  3622. this.y = y;
  3623. }
  3624. };
  3625. return CanvasExtraState;
  3626. })();
  3627. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3628. // Defines the time the executeOperatorList is going to be executing
  3629. // before it stops and shedules a continue of execution.
  3630. var EXECUTION_TIME = 15;
  3631. // Defines the number of steps before checking the execution time
  3632. var EXECUTION_STEPS = 10;
  3633. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3634. this.ctx = canvasCtx;
  3635. this.current = new CanvasExtraState();
  3636. this.stateStack = [];
  3637. this.pendingClip = null;
  3638. this.pendingEOFill = false;
  3639. this.res = null;
  3640. this.xobjs = null;
  3641. this.commonObjs = commonObjs;
  3642. this.objs = objs;
  3643. this.imageLayer = imageLayer;
  3644. this.groupStack = [];
  3645. this.processingType3 = null;
  3646. // Patterns are painted relative to the initial page/form transform, see pdf
  3647. // spec 8.7.2 NOTE 1.
  3648. this.baseTransform = null;
  3649. this.baseTransformStack = [];
  3650. this.groupLevel = 0;
  3651. this.smaskStack = [];
  3652. this.smaskCounter = 0;
  3653. this.tempSMask = null;
  3654. if (canvasCtx) {
  3655. addContextCurrentTransform(canvasCtx);
  3656. }
  3657. }
  3658. function putBinaryImageData(ctx, imgData) {
  3659. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3660. ctx.putImageData(imgData, 0, 0);
  3661. return;
  3662. }
  3663. // Put the image data to the canvas in chunks, rather than putting the
  3664. // whole image at once. This saves JS memory, because the ImageData object
  3665. // is smaller. It also possibly saves C++ memory within the implementation
  3666. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3667. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3668. // because too many putImageData() calls will slow things down.
  3669. //
  3670. // Note: as written, if the last chunk is partial, the putImageData() call
  3671. // will (conceptually) put pixels past the bounds of the canvas. But
  3672. // that's ok; any such pixels are ignored.
  3673. var height = imgData.height, width = imgData.width;
  3674. var fullChunkHeight = 16;
  3675. var fracChunks = height / fullChunkHeight;
  3676. var fullChunks = Math.floor(fracChunks);
  3677. var totalChunks = Math.ceil(fracChunks);
  3678. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3679. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3680. var srcPos = 0, destPos;
  3681. var src = imgData.data;
  3682. var dest = chunkImgData.data;
  3683. var i, j, thisChunkHeight, elemsInThisChunk;
  3684. // There are multiple forms in which the pixel data can be passed, and
  3685. // imgData.kind tells us which one this is.
  3686. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3687. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3688. var srcLength = src.byteLength;
  3689. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3690. new Uint32ArrayView(dest);
  3691. var dest32DataLength = dest32.length;
  3692. var fullSrcDiff = (width + 7) >> 3;
  3693. var white = 0xFFFFFFFF;
  3694. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3695. 0xFF000000 : 0x000000FF;
  3696. for (i = 0; i < totalChunks; i++) {
  3697. thisChunkHeight =
  3698. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3699. destPos = 0;
  3700. for (j = 0; j < thisChunkHeight; j++) {
  3701. var srcDiff = srcLength - srcPos;
  3702. var k = 0;
  3703. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3704. var kEndUnrolled = kEnd & ~7;
  3705. var mask = 0;
  3706. var srcByte = 0;
  3707. for (; k < kEndUnrolled; k += 8) {
  3708. srcByte = src[srcPos++];
  3709. dest32[destPos++] = (srcByte & 128) ? white : black;
  3710. dest32[destPos++] = (srcByte & 64) ? white : black;
  3711. dest32[destPos++] = (srcByte & 32) ? white : black;
  3712. dest32[destPos++] = (srcByte & 16) ? white : black;
  3713. dest32[destPos++] = (srcByte & 8) ? white : black;
  3714. dest32[destPos++] = (srcByte & 4) ? white : black;
  3715. dest32[destPos++] = (srcByte & 2) ? white : black;
  3716. dest32[destPos++] = (srcByte & 1) ? white : black;
  3717. }
  3718. for (; k < kEnd; k++) {
  3719. if (mask === 0) {
  3720. srcByte = src[srcPos++];
  3721. mask = 128;
  3722. }
  3723. dest32[destPos++] = (srcByte & mask) ? white : black;
  3724. mask >>= 1;
  3725. }
  3726. }
  3727. // We ran out of input. Make all remaining pixels transparent.
  3728. while (destPos < dest32DataLength) {
  3729. dest32[destPos++] = 0;
  3730. }
  3731. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3732. }
  3733. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3734. // RGBA, 32-bits per pixel.
  3735. j = 0;
  3736. elemsInThisChunk = width * fullChunkHeight * 4;
  3737. for (i = 0; i < fullChunks; i++) {
  3738. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3739. srcPos += elemsInThisChunk;
  3740. ctx.putImageData(chunkImgData, 0, j);
  3741. j += fullChunkHeight;
  3742. }
  3743. if (i < totalChunks) {
  3744. elemsInThisChunk = width * partialChunkHeight * 4;
  3745. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3746. ctx.putImageData(chunkImgData, 0, j);
  3747. }
  3748. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3749. // RGB, 24-bits per pixel.
  3750. thisChunkHeight = fullChunkHeight;
  3751. elemsInThisChunk = width * thisChunkHeight;
  3752. for (i = 0; i < totalChunks; i++) {
  3753. if (i >= fullChunks) {
  3754. thisChunkHeight =partialChunkHeight;
  3755. elemsInThisChunk = width * thisChunkHeight;
  3756. }
  3757. destPos = 0;
  3758. for (j = elemsInThisChunk; j--;) {
  3759. dest[destPos++] = src[srcPos++];
  3760. dest[destPos++] = src[srcPos++];
  3761. dest[destPos++] = src[srcPos++];
  3762. dest[destPos++] = 255;
  3763. }
  3764. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3765. }
  3766. } else {
  3767. error('bad image kind: ' + imgData.kind);
  3768. }
  3769. }
  3770. function putBinaryImageMask(ctx, imgData) {
  3771. var height = imgData.height, width = imgData.width;
  3772. var fullChunkHeight = 16;
  3773. var fracChunks = height / fullChunkHeight;
  3774. var fullChunks = Math.floor(fracChunks);
  3775. var totalChunks = Math.ceil(fracChunks);
  3776. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3777. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3778. var srcPos = 0;
  3779. var src = imgData.data;
  3780. var dest = chunkImgData.data;
  3781. for (var i = 0; i < totalChunks; i++) {
  3782. var thisChunkHeight =
  3783. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3784. // Expand the mask so it can be used by the canvas. Any required
  3785. // inversion has already been handled.
  3786. var destPos = 3; // alpha component offset
  3787. for (var j = 0; j < thisChunkHeight; j++) {
  3788. var mask = 0;
  3789. for (var k = 0; k < width; k++) {
  3790. if (!mask) {
  3791. var elem = src[srcPos++];
  3792. mask = 128;
  3793. }
  3794. dest[destPos] = (elem & mask) ? 0 : 255;
  3795. destPos += 4;
  3796. mask >>= 1;
  3797. }
  3798. }
  3799. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3800. }
  3801. }
  3802. function copyCtxState(sourceCtx, destCtx) {
  3803. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3804. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3805. 'globalCompositeOperation', 'font'];
  3806. for (var i = 0, ii = properties.length; i < ii; i++) {
  3807. var property = properties[i];
  3808. if (property in sourceCtx) {
  3809. destCtx[property] = sourceCtx[property];
  3810. }
  3811. }
  3812. if ('setLineDash' in sourceCtx) {
  3813. destCtx.setLineDash(sourceCtx.getLineDash());
  3814. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3815. } else if ('mozDash' in sourceCtx) {
  3816. destCtx.mozDash = sourceCtx.mozDash;
  3817. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3818. }
  3819. }
  3820. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3821. var length = bytes.length;
  3822. for (var i = 3; i < length; i += 4) {
  3823. var alpha = bytes[i];
  3824. if (alpha === 0) {
  3825. bytes[i - 3] = r0;
  3826. bytes[i - 2] = g0;
  3827. bytes[i - 1] = b0;
  3828. } else if (alpha < 255) {
  3829. var alpha_ = 255 - alpha;
  3830. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3831. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3832. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3833. }
  3834. }
  3835. }
  3836. function composeSMaskAlpha(maskData, layerData) {
  3837. var length = maskData.length;
  3838. var scale = 1 / 255;
  3839. for (var i = 3; i < length; i += 4) {
  3840. var alpha = maskData[i];
  3841. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3842. }
  3843. }
  3844. function composeSMaskLuminosity(maskData, layerData) {
  3845. var length = maskData.length;
  3846. for (var i = 3; i < length; i += 4) {
  3847. var y = ((maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3848. (maskData[i - 2] * 152) + // * 0.59 ....
  3849. (maskData[i - 1] * 28)) | 0; // * 0.11 ....
  3850. layerData[i] = (layerData[i] * y) >> 16;
  3851. }
  3852. }
  3853. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3854. subtype, backdrop) {
  3855. var hasBackdrop = backdrop !== undefined;
  3856. var r0 = hasBackdrop ? backdrop[0] : 0;
  3857. var g0 = hasBackdrop ? backdrop[1] : 0;
  3858. var b0 = hasBackdrop ? backdrop[2] : 0;
  3859. var composeFn;
  3860. if (subtype === 'Luminosity') {
  3861. composeFn = composeSMaskLuminosity;
  3862. } else {
  3863. composeFn = composeSMaskAlpha;
  3864. }
  3865. // processing image in chunks to save memory
  3866. var PIXELS_TO_PROCESS = 65536;
  3867. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3868. for (var row = 0; row < height; row += chunkSize) {
  3869. var chunkHeight = Math.min(chunkSize, height - row);
  3870. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3871. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3872. if (hasBackdrop) {
  3873. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3874. }
  3875. composeFn(maskData.data, layerData.data);
  3876. maskCtx.putImageData(layerData, 0, row);
  3877. }
  3878. }
  3879. function composeSMask(ctx, smask, layerCtx) {
  3880. var mask = smask.canvas;
  3881. var maskCtx = smask.context;
  3882. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3883. smask.offsetX, smask.offsetY);
  3884. var backdrop = smask.backdrop || null;
  3885. if (WebGLUtils.isEnabled) {
  3886. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3887. {subtype: smask.subtype, backdrop: backdrop});
  3888. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3889. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3890. return;
  3891. }
  3892. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3893. smask.subtype, backdrop);
  3894. ctx.drawImage(mask, 0, 0);
  3895. }
  3896. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3897. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3898. var NORMAL_CLIP = {};
  3899. var EO_CLIP = {};
  3900. CanvasGraphics.prototype = {
  3901. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3902. // For pdfs that use blend modes we have to clear the canvas else certain
  3903. // blend modes can look wrong since we'd be blending with a white
  3904. // backdrop. The problem with a transparent backdrop though is we then
  3905. // don't get sub pixel anti aliasing on text, so we fill with white if
  3906. // we can.
  3907. var width = this.ctx.canvas.width;
  3908. var height = this.ctx.canvas.height;
  3909. if (transparency) {
  3910. this.ctx.clearRect(0, 0, width, height);
  3911. } else {
  3912. this.ctx.mozOpaque = true;
  3913. this.ctx.save();
  3914. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3915. this.ctx.fillRect(0, 0, width, height);
  3916. this.ctx.restore();
  3917. }
  3918. var transform = viewport.transform;
  3919. this.ctx.save();
  3920. this.ctx.transform.apply(this.ctx, transform);
  3921. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3922. if (this.imageLayer) {
  3923. this.imageLayer.beginLayout();
  3924. }
  3925. },
  3926. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3927. operatorList,
  3928. executionStartIdx, continueCallback,
  3929. stepper) {
  3930. var argsArray = operatorList.argsArray;
  3931. var fnArray = operatorList.fnArray;
  3932. var i = executionStartIdx || 0;
  3933. var argsArrayLen = argsArray.length;
  3934. // Sometimes the OperatorList to execute is empty.
  3935. if (argsArrayLen === i) {
  3936. return i;
  3937. }
  3938. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3939. typeof continueCallback === 'function');
  3940. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3941. var steps = 0;
  3942. var commonObjs = this.commonObjs;
  3943. var objs = this.objs;
  3944. var fnId;
  3945. while (true) {
  3946. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3947. stepper.breakIt(i, continueCallback);
  3948. return i;
  3949. }
  3950. fnId = fnArray[i];
  3951. if (fnId !== OPS.dependency) {
  3952. this[fnId].apply(this, argsArray[i]);
  3953. } else {
  3954. var deps = argsArray[i];
  3955. for (var n = 0, nn = deps.length; n < nn; n++) {
  3956. var depObjId = deps[n];
  3957. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3958. var objsPool = common ? commonObjs : objs;
  3959. // If the promise isn't resolved yet, add the continueCallback
  3960. // to the promise and bail out.
  3961. if (!objsPool.isResolved(depObjId)) {
  3962. objsPool.get(depObjId, continueCallback);
  3963. return i;
  3964. }
  3965. }
  3966. }
  3967. i++;
  3968. // If the entire operatorList was executed, stop as were done.
  3969. if (i === argsArrayLen) {
  3970. return i;
  3971. }
  3972. // If the execution took longer then a certain amount of time and
  3973. // `continueCallback` is specified, interrupt the execution.
  3974. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3975. if (Date.now() > endTime) {
  3976. continueCallback();
  3977. return i;
  3978. }
  3979. steps = 0;
  3980. }
  3981. // If the operatorList isn't executed completely yet OR the execution
  3982. // time was short enough, do another execution round.
  3983. }
  3984. },
  3985. endDrawing: function CanvasGraphics_endDrawing() {
  3986. this.ctx.restore();
  3987. CachedCanvases.clear();
  3988. WebGLUtils.clear();
  3989. if (this.imageLayer) {
  3990. this.imageLayer.endLayout();
  3991. }
  3992. },
  3993. // Graphics state
  3994. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3995. this.current.lineWidth = width;
  3996. this.ctx.lineWidth = width;
  3997. },
  3998. setLineCap: function CanvasGraphics_setLineCap(style) {
  3999. this.ctx.lineCap = LINE_CAP_STYLES[style];
  4000. },
  4001. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  4002. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  4003. },
  4004. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  4005. this.ctx.miterLimit = limit;
  4006. },
  4007. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  4008. var ctx = this.ctx;
  4009. if ('setLineDash' in ctx) {
  4010. ctx.setLineDash(dashArray);
  4011. ctx.lineDashOffset = dashPhase;
  4012. } else {
  4013. ctx.mozDash = dashArray;
  4014. ctx.mozDashOffset = dashPhase;
  4015. }
  4016. },
  4017. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  4018. // Maybe if we one day fully support color spaces this will be important
  4019. // for now we can ignore.
  4020. // TODO set rendering intent?
  4021. },
  4022. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  4023. // There's no way to control this with canvas, but we can safely ignore.
  4024. // TODO set flatness?
  4025. },
  4026. setGState: function CanvasGraphics_setGState(states) {
  4027. for (var i = 0, ii = states.length; i < ii; i++) {
  4028. var state = states[i];
  4029. var key = state[0];
  4030. var value = state[1];
  4031. switch (key) {
  4032. case 'LW':
  4033. this.setLineWidth(value);
  4034. break;
  4035. case 'LC':
  4036. this.setLineCap(value);
  4037. break;
  4038. case 'LJ':
  4039. this.setLineJoin(value);
  4040. break;
  4041. case 'ML':
  4042. this.setMiterLimit(value);
  4043. break;
  4044. case 'D':
  4045. this.setDash(value[0], value[1]);
  4046. break;
  4047. case 'RI':
  4048. this.setRenderingIntent(value);
  4049. break;
  4050. case 'FL':
  4051. this.setFlatness(value);
  4052. break;
  4053. case 'Font':
  4054. this.setFont(value[0], value[1]);
  4055. break;
  4056. case 'CA':
  4057. this.current.strokeAlpha = state[1];
  4058. break;
  4059. case 'ca':
  4060. this.current.fillAlpha = state[1];
  4061. this.ctx.globalAlpha = state[1];
  4062. break;
  4063. case 'BM':
  4064. if (value && value.name && (value.name !== 'Normal')) {
  4065. var mode = value.name.replace(/([A-Z])/g,
  4066. function(c) {
  4067. return '-' + c.toLowerCase();
  4068. }
  4069. ).substring(1);
  4070. this.ctx.globalCompositeOperation = mode;
  4071. if (this.ctx.globalCompositeOperation !== mode) {
  4072. warn('globalCompositeOperation "' + mode +
  4073. '" is not supported');
  4074. }
  4075. } else {
  4076. this.ctx.globalCompositeOperation = 'source-over';
  4077. }
  4078. break;
  4079. case 'SMask':
  4080. if (this.current.activeSMask) {
  4081. this.endSMaskGroup();
  4082. }
  4083. this.current.activeSMask = value ? this.tempSMask : null;
  4084. if (this.current.activeSMask) {
  4085. this.beginSMaskGroup();
  4086. }
  4087. this.tempSMask = null;
  4088. break;
  4089. }
  4090. }
  4091. },
  4092. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  4093. var activeSMask = this.current.activeSMask;
  4094. var drawnWidth = activeSMask.canvas.width;
  4095. var drawnHeight = activeSMask.canvas.height;
  4096. var cacheId = 'smaskGroupAt' + this.groupLevel;
  4097. var scratchCanvas = CachedCanvases.getCanvas(
  4098. cacheId, drawnWidth, drawnHeight, true);
  4099. var currentCtx = this.ctx;
  4100. var currentTransform = currentCtx.mozCurrentTransform;
  4101. this.ctx.save();
  4102. var groupCtx = scratchCanvas.context;
  4103. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  4104. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  4105. groupCtx.transform.apply(groupCtx, currentTransform);
  4106. copyCtxState(currentCtx, groupCtx);
  4107. this.ctx = groupCtx;
  4108. this.setGState([
  4109. ['BM', 'Normal'],
  4110. ['ca', 1],
  4111. ['CA', 1]
  4112. ]);
  4113. this.groupStack.push(currentCtx);
  4114. this.groupLevel++;
  4115. },
  4116. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  4117. var groupCtx = this.ctx;
  4118. this.groupLevel--;
  4119. this.ctx = this.groupStack.pop();
  4120. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4121. this.ctx.restore();
  4122. },
  4123. save: function CanvasGraphics_save() {
  4124. this.ctx.save();
  4125. var old = this.current;
  4126. this.stateStack.push(old);
  4127. this.current = old.clone();
  4128. this.current.activeSMask = null;
  4129. },
  4130. restore: function CanvasGraphics_restore() {
  4131. if (this.stateStack.length !== 0) {
  4132. if (this.current.activeSMask !== null) {
  4133. this.endSMaskGroup();
  4134. }
  4135. this.current = this.stateStack.pop();
  4136. this.ctx.restore();
  4137. }
  4138. },
  4139. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  4140. this.ctx.transform(a, b, c, d, e, f);
  4141. },
  4142. // Path
  4143. constructPath: function CanvasGraphics_constructPath(ops, args) {
  4144. var ctx = this.ctx;
  4145. var current = this.current;
  4146. var x = current.x, y = current.y;
  4147. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  4148. switch (ops[i] | 0) {
  4149. case OPS.moveTo:
  4150. x = args[j++];
  4151. y = args[j++];
  4152. ctx.moveTo(x, y);
  4153. break;
  4154. case OPS.lineTo:
  4155. x = args[j++];
  4156. y = args[j++];
  4157. ctx.lineTo(x, y);
  4158. break;
  4159. case OPS.curveTo:
  4160. x = args[j + 4];
  4161. y = args[j + 5];
  4162. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  4163. x, y);
  4164. j += 6;
  4165. break;
  4166. case OPS.curveTo2:
  4167. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  4168. args[j + 2], args[j + 3]);
  4169. x = args[j + 2];
  4170. y = args[j + 3];
  4171. j += 4;
  4172. break;
  4173. case OPS.curveTo3:
  4174. x = args[j + 2];
  4175. y = args[j + 3];
  4176. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  4177. j += 4;
  4178. break;
  4179. case OPS.closePath:
  4180. ctx.closePath();
  4181. break;
  4182. }
  4183. }
  4184. current.setCurrentPoint(x, y);
  4185. },
  4186. closePath: function CanvasGraphics_closePath() {
  4187. this.ctx.closePath();
  4188. },
  4189. rectangle: function CanvasGraphics_rectangle(x, y, width, height) {
  4190. if (width === 0) {
  4191. width = this.getSinglePixelWidth();
  4192. }
  4193. if (height === 0) {
  4194. height = this.getSinglePixelWidth();
  4195. }
  4196. this.ctx.rect(x, y, width, height);
  4197. },
  4198. stroke: function CanvasGraphics_stroke(consumePath) {
  4199. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  4200. var ctx = this.ctx;
  4201. var strokeColor = this.current.strokeColor;
  4202. if (this.current.lineWidth === 0) {
  4203. ctx.lineWidth = this.getSinglePixelWidth();
  4204. }
  4205. // For stroke we want to temporarily change the global alpha to the
  4206. // stroking alpha.
  4207. ctx.globalAlpha = this.current.strokeAlpha;
  4208. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  4209. strokeColor.type === 'Pattern') {
  4210. // for patterns, we transform to pattern space, calculate
  4211. // the pattern, call stroke, and restore to user space
  4212. ctx.save();
  4213. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  4214. ctx.stroke();
  4215. ctx.restore();
  4216. } else {
  4217. ctx.stroke();
  4218. }
  4219. if (consumePath) {
  4220. this.consumePath();
  4221. }
  4222. // Restore the global alpha to the fill alpha
  4223. ctx.globalAlpha = this.current.fillAlpha;
  4224. },
  4225. closeStroke: function CanvasGraphics_closeStroke() {
  4226. this.closePath();
  4227. this.stroke();
  4228. },
  4229. fill: function CanvasGraphics_fill(consumePath) {
  4230. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  4231. var ctx = this.ctx;
  4232. var fillColor = this.current.fillColor;
  4233. var needRestore = false;
  4234. if (fillColor && fillColor.hasOwnProperty('type') &&
  4235. fillColor.type === 'Pattern') {
  4236. ctx.save();
  4237. ctx.fillStyle = fillColor.getPattern(ctx, this);
  4238. needRestore = true;
  4239. }
  4240. if (this.pendingEOFill) {
  4241. if (ctx.mozFillRule !== undefined) {
  4242. ctx.mozFillRule = 'evenodd';
  4243. ctx.fill();
  4244. ctx.mozFillRule = 'nonzero';
  4245. } else {
  4246. try {
  4247. ctx.fill('evenodd');
  4248. } catch (ex) {
  4249. // shouldn't really happen, but browsers might think differently
  4250. ctx.fill();
  4251. }
  4252. }
  4253. this.pendingEOFill = false;
  4254. } else {
  4255. ctx.fill();
  4256. }
  4257. if (needRestore) {
  4258. ctx.restore();
  4259. }
  4260. if (consumePath) {
  4261. this.consumePath();
  4262. }
  4263. },
  4264. eoFill: function CanvasGraphics_eoFill() {
  4265. this.pendingEOFill = true;
  4266. this.fill();
  4267. },
  4268. fillStroke: function CanvasGraphics_fillStroke() {
  4269. this.fill(false);
  4270. this.stroke(false);
  4271. this.consumePath();
  4272. },
  4273. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  4274. this.pendingEOFill = true;
  4275. this.fillStroke();
  4276. },
  4277. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  4278. this.closePath();
  4279. this.fillStroke();
  4280. },
  4281. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  4282. this.pendingEOFill = true;
  4283. this.closePath();
  4284. this.fillStroke();
  4285. },
  4286. endPath: function CanvasGraphics_endPath() {
  4287. this.consumePath();
  4288. },
  4289. // Clipping
  4290. clip: function CanvasGraphics_clip() {
  4291. this.pendingClip = NORMAL_CLIP;
  4292. },
  4293. eoClip: function CanvasGraphics_eoClip() {
  4294. this.pendingClip = EO_CLIP;
  4295. },
  4296. // Text
  4297. beginText: function CanvasGraphics_beginText() {
  4298. this.current.textMatrix = IDENTITY_MATRIX;
  4299. this.current.textMatrixScale = 1;
  4300. this.current.x = this.current.lineX = 0;
  4301. this.current.y = this.current.lineY = 0;
  4302. },
  4303. endText: function CanvasGraphics_endText() {
  4304. var paths = this.pendingTextPaths;
  4305. var ctx = this.ctx;
  4306. if (paths === undefined) {
  4307. ctx.beginPath();
  4308. return;
  4309. }
  4310. ctx.save();
  4311. ctx.beginPath();
  4312. for (var i = 0; i < paths.length; i++) {
  4313. var path = paths[i];
  4314. ctx.setTransform.apply(ctx, path.transform);
  4315. ctx.translate(path.x, path.y);
  4316. path.addToPath(ctx, path.fontSize);
  4317. }
  4318. ctx.restore();
  4319. ctx.clip();
  4320. ctx.beginPath();
  4321. delete this.pendingTextPaths;
  4322. },
  4323. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  4324. this.current.charSpacing = spacing;
  4325. },
  4326. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  4327. this.current.wordSpacing = spacing;
  4328. },
  4329. setHScale: function CanvasGraphics_setHScale(scale) {
  4330. this.current.textHScale = scale / 100;
  4331. },
  4332. setLeading: function CanvasGraphics_setLeading(leading) {
  4333. this.current.leading = -leading;
  4334. },
  4335. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  4336. var fontObj = this.commonObjs.get(fontRefName);
  4337. var current = this.current;
  4338. if (!fontObj) {
  4339. error('Can\'t find font for ' + fontRefName);
  4340. }
  4341. current.fontMatrix = (fontObj.fontMatrix ?
  4342. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4343. // A valid matrix needs all main diagonal elements to be non-zero
  4344. // This also ensures we bypass FF bugzilla bug #719844.
  4345. if (current.fontMatrix[0] === 0 ||
  4346. current.fontMatrix[3] === 0) {
  4347. warn('Invalid font matrix for font ' + fontRefName);
  4348. }
  4349. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4350. // and in some docs this can be negative (inverted x-y axes).
  4351. if (size < 0) {
  4352. size = -size;
  4353. current.fontDirection = -1;
  4354. } else {
  4355. current.fontDirection = 1;
  4356. }
  4357. this.current.font = fontObj;
  4358. this.current.fontSize = size;
  4359. if (fontObj.isType3Font) {
  4360. return; // we don't need ctx.font for Type3 fonts
  4361. }
  4362. var name = fontObj.loadedName || 'sans-serif';
  4363. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  4364. (fontObj.bold ? 'bold' : 'normal');
  4365. var italic = fontObj.italic ? 'italic' : 'normal';
  4366. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4367. // Some font backends cannot handle fonts below certain size.
  4368. // Keeping the font at minimal size and using the fontSizeScale to change
  4369. // the current transformation matrix before the fillText/strokeText.
  4370. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4371. var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
  4372. this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :
  4373. size / MIN_FONT_SIZE;
  4374. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4375. this.ctx.font = rule;
  4376. },
  4377. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4378. this.current.textRenderingMode = mode;
  4379. },
  4380. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4381. this.current.textRise = rise;
  4382. },
  4383. moveText: function CanvasGraphics_moveText(x, y) {
  4384. this.current.x = this.current.lineX += x;
  4385. this.current.y = this.current.lineY += y;
  4386. },
  4387. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4388. this.setLeading(-y);
  4389. this.moveText(x, y);
  4390. },
  4391. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4392. this.current.textMatrix = [a, b, c, d, e, f];
  4393. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4394. this.current.x = this.current.lineX = 0;
  4395. this.current.y = this.current.lineY = 0;
  4396. },
  4397. nextLine: function CanvasGraphics_nextLine() {
  4398. this.moveText(0, this.current.leading);
  4399. },
  4400. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4401. var ctx = this.ctx;
  4402. var current = this.current;
  4403. var font = current.font;
  4404. var textRenderingMode = current.textRenderingMode;
  4405. var fontSize = current.fontSize / current.fontSizeScale;
  4406. var fillStrokeMode = textRenderingMode &
  4407. TextRenderingMode.FILL_STROKE_MASK;
  4408. var isAddToPathSet = !!(textRenderingMode &
  4409. TextRenderingMode.ADD_TO_PATH_FLAG);
  4410. var addToPath;
  4411. if (font.disableFontFace || isAddToPathSet) {
  4412. addToPath = font.getPathGenerator(this.commonObjs, character);
  4413. }
  4414. if (font.disableFontFace) {
  4415. ctx.save();
  4416. ctx.translate(x, y);
  4417. ctx.beginPath();
  4418. addToPath(ctx, fontSize);
  4419. if (fillStrokeMode === TextRenderingMode.FILL ||
  4420. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4421. ctx.fill();
  4422. }
  4423. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4424. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4425. ctx.stroke();
  4426. }
  4427. ctx.restore();
  4428. } else {
  4429. if (fillStrokeMode === TextRenderingMode.FILL ||
  4430. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4431. ctx.fillText(character, x, y);
  4432. }
  4433. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4434. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4435. ctx.strokeText(character, x, y);
  4436. }
  4437. }
  4438. if (isAddToPathSet) {
  4439. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4440. paths.push({
  4441. transform: ctx.mozCurrentTransform,
  4442. x: x,
  4443. y: y,
  4444. fontSize: fontSize,
  4445. addToPath: addToPath
  4446. });
  4447. }
  4448. },
  4449. get isFontSubpixelAAEnabled() {
  4450. // Checks if anti-aliasing is enabled when scaled text is painted.
  4451. // On Windows GDI scaled fonts looks bad.
  4452. var ctx = document.createElement('canvas').getContext('2d');
  4453. ctx.scale(1.5, 1);
  4454. ctx.fillText('I', 0, 10);
  4455. var data = ctx.getImageData(0, 0, 10, 10).data;
  4456. var enabled = false;
  4457. for (var i = 3; i < data.length; i += 4) {
  4458. if (data[i] > 0 && data[i] < 255) {
  4459. enabled = true;
  4460. break;
  4461. }
  4462. }
  4463. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4464. },
  4465. showText: function CanvasGraphics_showText(glyphs) {
  4466. var current = this.current;
  4467. var font = current.font;
  4468. if (font.isType3Font) {
  4469. return this.showType3Text(glyphs);
  4470. }
  4471. var fontSize = current.fontSize;
  4472. if (fontSize === 0) {
  4473. return;
  4474. }
  4475. var ctx = this.ctx;
  4476. var fontSizeScale = current.fontSizeScale;
  4477. var charSpacing = current.charSpacing;
  4478. var wordSpacing = current.wordSpacing;
  4479. var fontDirection = current.fontDirection;
  4480. var textHScale = current.textHScale * fontDirection;
  4481. var glyphsLength = glyphs.length;
  4482. var vertical = font.vertical;
  4483. var defaultVMetrics = font.defaultVMetrics;
  4484. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4485. var simpleFillText =
  4486. current.textRenderingMode === TextRenderingMode.FILL &&
  4487. !font.disableFontFace;
  4488. ctx.save();
  4489. ctx.transform.apply(ctx, current.textMatrix);
  4490. ctx.translate(current.x, current.y + current.textRise);
  4491. if (fontDirection > 0) {
  4492. ctx.scale(textHScale, -1);
  4493. } else {
  4494. ctx.scale(textHScale, 1);
  4495. }
  4496. var lineWidth = current.lineWidth;
  4497. var scale = current.textMatrixScale;
  4498. if (scale === 0 || lineWidth === 0) {
  4499. lineWidth = this.getSinglePixelWidth();
  4500. } else {
  4501. lineWidth /= scale;
  4502. }
  4503. if (fontSizeScale != 1.0) {
  4504. ctx.scale(fontSizeScale, fontSizeScale);
  4505. lineWidth /= fontSizeScale;
  4506. }
  4507. ctx.lineWidth = lineWidth;
  4508. var x = 0, i;
  4509. for (i = 0; i < glyphsLength; ++i) {
  4510. var glyph = glyphs[i];
  4511. if (glyph === null) {
  4512. // word break
  4513. x += fontDirection * wordSpacing;
  4514. continue;
  4515. } else if (isNum(glyph)) {
  4516. x += -glyph * fontSize * 0.001;
  4517. continue;
  4518. }
  4519. var restoreNeeded = false;
  4520. var character = glyph.fontChar;
  4521. var accent = glyph.accent;
  4522. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4523. var width = glyph.width;
  4524. if (vertical) {
  4525. var vmetric, vx, vy;
  4526. vmetric = glyph.vmetric || defaultVMetrics;
  4527. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4528. vx = -vx * widthAdvanceScale;
  4529. vy = vmetric[2] * widthAdvanceScale;
  4530. width = vmetric ? -vmetric[0] : width;
  4531. scaledX = vx / fontSizeScale;
  4532. scaledY = (x + vy) / fontSizeScale;
  4533. } else {
  4534. scaledX = x / fontSizeScale;
  4535. scaledY = 0;
  4536. }
  4537. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4538. // some standard fonts may not have the exact width, trying to
  4539. // rescale per character
  4540. var measuredWidth = ctx.measureText(character).width * 1000 /
  4541. fontSize * fontSizeScale;
  4542. var characterScaleX = width / measuredWidth;
  4543. restoreNeeded = true;
  4544. ctx.save();
  4545. ctx.scale(characterScaleX, 1);
  4546. scaledX /= characterScaleX;
  4547. }
  4548. if (simpleFillText && !accent) {
  4549. // common case
  4550. ctx.fillText(character, scaledX, scaledY);
  4551. } else {
  4552. this.paintChar(character, scaledX, scaledY);
  4553. if (accent) {
  4554. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4555. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4556. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4557. }
  4558. }
  4559. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4560. x += charWidth;
  4561. if (restoreNeeded) {
  4562. ctx.restore();
  4563. }
  4564. }
  4565. if (vertical) {
  4566. current.y -= x * textHScale;
  4567. } else {
  4568. current.x += x * textHScale;
  4569. }
  4570. ctx.restore();
  4571. },
  4572. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4573. // Type3 fonts - each glyph is a "mini-PDF"
  4574. var ctx = this.ctx;
  4575. var current = this.current;
  4576. var font = current.font;
  4577. var fontSize = current.fontSize;
  4578. var fontDirection = current.fontDirection;
  4579. var charSpacing = current.charSpacing;
  4580. var wordSpacing = current.wordSpacing;
  4581. var textHScale = current.textHScale * fontDirection;
  4582. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4583. var glyphsLength = glyphs.length;
  4584. var i, glyph, width;
  4585. if (fontSize === 0) {
  4586. return;
  4587. }
  4588. ctx.save();
  4589. ctx.transform.apply(ctx, current.textMatrix);
  4590. ctx.translate(current.x, current.y);
  4591. ctx.scale(textHScale, 1);
  4592. for (i = 0; i < glyphsLength; ++i) {
  4593. glyph = glyphs[i];
  4594. if (glyph === null) {
  4595. // word break
  4596. this.ctx.translate(wordSpacing, 0);
  4597. current.x += wordSpacing * textHScale;
  4598. continue;
  4599. } else if (isNum(glyph)) {
  4600. var spacingLength = -glyph * 0.001 * fontSize;
  4601. this.ctx.translate(spacingLength, 0);
  4602. current.x += spacingLength * textHScale;
  4603. continue;
  4604. }
  4605. this.processingType3 = glyph;
  4606. this.save();
  4607. ctx.scale(fontSize, fontSize);
  4608. ctx.transform.apply(ctx, fontMatrix);
  4609. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4610. this.executeOperatorList(operatorList);
  4611. this.restore();
  4612. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4613. width = ((transformed[0] * fontSize + charSpacing) * fontDirection);
  4614. ctx.translate(width, 0);
  4615. current.x += width * textHScale;
  4616. }
  4617. ctx.restore();
  4618. this.processingType3 = null;
  4619. },
  4620. // Type3 fonts
  4621. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4622. // We can safely ignore this since the width should be the same
  4623. // as the width in the Widths array.
  4624. },
  4625. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4626. yWidth,
  4627. llx,
  4628. lly,
  4629. urx,
  4630. ury) {
  4631. // TODO According to the spec we're also suppose to ignore any operators
  4632. // that set color or include images while processing this type3 font.
  4633. this.rectangle(llx, lly, urx - llx, ury - lly);
  4634. this.clip();
  4635. this.endPath();
  4636. },
  4637. // Color
  4638. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4639. var pattern;
  4640. if (IR[0] === 'TilingPattern') {
  4641. var color = IR[1];
  4642. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4643. this.commonObjs, this.baseTransform);
  4644. } else {
  4645. pattern = getShadingPatternFromIR(IR);
  4646. }
  4647. return pattern;
  4648. },
  4649. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4650. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4651. },
  4652. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4653. this.current.fillColor = this.getColorN_Pattern(arguments);
  4654. },
  4655. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4656. var color = Util.makeCssRgb(arguments);
  4657. this.ctx.strokeStyle = color;
  4658. this.current.strokeColor = color;
  4659. },
  4660. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4661. var color = Util.makeCssRgb(arguments);
  4662. this.ctx.fillStyle = color;
  4663. this.current.fillColor = color;
  4664. },
  4665. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4666. var ctx = this.ctx;
  4667. this.save();
  4668. var pattern = getShadingPatternFromIR(patternIR);
  4669. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4670. var inv = ctx.mozCurrentTransformInverse;
  4671. if (inv) {
  4672. var canvas = ctx.canvas;
  4673. var width = canvas.width;
  4674. var height = canvas.height;
  4675. var bl = Util.applyTransform([0, 0], inv);
  4676. var br = Util.applyTransform([0, height], inv);
  4677. var ul = Util.applyTransform([width, 0], inv);
  4678. var ur = Util.applyTransform([width, height], inv);
  4679. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4680. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4681. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4682. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4683. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4684. } else {
  4685. // HACK to draw the gradient onto an infinite rectangle.
  4686. // PDF gradients are drawn across the entire image while
  4687. // Canvas only allows gradients to be drawn in a rectangle
  4688. // The following bug should allow us to remove this.
  4689. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4690. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4691. }
  4692. this.restore();
  4693. },
  4694. // Images
  4695. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4696. error('Should not call beginInlineImage');
  4697. },
  4698. beginImageData: function CanvasGraphics_beginImageData() {
  4699. error('Should not call beginImageData');
  4700. },
  4701. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4702. bbox) {
  4703. this.save();
  4704. this.baseTransformStack.push(this.baseTransform);
  4705. if (isArray(matrix) && 6 === matrix.length) {
  4706. this.transform.apply(this, matrix);
  4707. }
  4708. this.baseTransform = this.ctx.mozCurrentTransform;
  4709. if (isArray(bbox) && 4 === bbox.length) {
  4710. var width = bbox[2] - bbox[0];
  4711. var height = bbox[3] - bbox[1];
  4712. this.rectangle(bbox[0], bbox[1], width, height);
  4713. this.clip();
  4714. this.endPath();
  4715. }
  4716. },
  4717. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4718. this.restore();
  4719. this.baseTransform = this.baseTransformStack.pop();
  4720. },
  4721. beginGroup: function CanvasGraphics_beginGroup(group) {
  4722. this.save();
  4723. var currentCtx = this.ctx;
  4724. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4725. // group results aren't usually that different and they even have tools
  4726. // that ignore this setting. Notes from Rik on implmenting:
  4727. // - When you encounter an transparency group, create a new canvas with
  4728. // the dimensions of the bbox
  4729. // - copy the content from the previous canvas to the new canvas
  4730. // - draw as usual
  4731. // - remove the backdrop alpha:
  4732. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4733. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4734. // backdrop
  4735. // - remove background color:
  4736. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4737. if (!group.isolated) {
  4738. info('TODO: Support non-isolated groups.');
  4739. }
  4740. // TODO knockout - supposedly possible with the clever use of compositing
  4741. // modes.
  4742. if (group.knockout) {
  4743. warn('Knockout groups not supported.');
  4744. }
  4745. var currentTransform = currentCtx.mozCurrentTransform;
  4746. if (group.matrix) {
  4747. currentCtx.transform.apply(currentCtx, group.matrix);
  4748. }
  4749. assert(group.bbox, 'Bounding box is required.');
  4750. // Based on the current transform figure out how big the bounding box
  4751. // will actually be.
  4752. var bounds = Util.getAxialAlignedBoundingBox(
  4753. group.bbox,
  4754. currentCtx.mozCurrentTransform);
  4755. // Clip the bounding box to the current canvas.
  4756. var canvasBounds = [0,
  4757. 0,
  4758. currentCtx.canvas.width,
  4759. currentCtx.canvas.height];
  4760. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4761. // Use ceil in case we're between sizes so we don't create canvas that is
  4762. // too small and make the canvas at least 1x1 pixels.
  4763. var offsetX = Math.floor(bounds[0]);
  4764. var offsetY = Math.floor(bounds[1]);
  4765. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4766. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4767. var scaleX = 1, scaleY = 1;
  4768. if (drawnWidth > MAX_GROUP_SIZE) {
  4769. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4770. drawnWidth = MAX_GROUP_SIZE;
  4771. }
  4772. if (drawnHeight > MAX_GROUP_SIZE) {
  4773. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4774. drawnHeight = MAX_GROUP_SIZE;
  4775. }
  4776. var cacheId = 'groupAt' + this.groupLevel;
  4777. if (group.smask) {
  4778. // Using two cache entries is case if masks are used one after another.
  4779. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4780. }
  4781. var scratchCanvas = CachedCanvases.getCanvas(
  4782. cacheId, drawnWidth, drawnHeight, true);
  4783. var groupCtx = scratchCanvas.context;
  4784. // Since we created a new canvas that is just the size of the bounding box
  4785. // we have to translate the group ctx.
  4786. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4787. groupCtx.translate(-offsetX, -offsetY);
  4788. groupCtx.transform.apply(groupCtx, currentTransform);
  4789. if (group.smask) {
  4790. // Saving state and cached mask to be used in setGState.
  4791. this.smaskStack.push({
  4792. canvas: scratchCanvas.canvas,
  4793. context: groupCtx,
  4794. offsetX: offsetX,
  4795. offsetY: offsetY,
  4796. scaleX: scaleX,
  4797. scaleY: scaleY,
  4798. subtype: group.smask.subtype,
  4799. backdrop: group.smask.backdrop
  4800. });
  4801. } else {
  4802. // Setup the current ctx so when the group is popped we draw it at the
  4803. // right location.
  4804. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4805. currentCtx.translate(offsetX, offsetY);
  4806. currentCtx.scale(scaleX, scaleY);
  4807. }
  4808. // The transparency group inherits all off the current graphics state
  4809. // except the blend mode, soft mask, and alpha constants.
  4810. copyCtxState(currentCtx, groupCtx);
  4811. this.ctx = groupCtx;
  4812. this.setGState([
  4813. ['BM', 'Normal'],
  4814. ['ca', 1],
  4815. ['CA', 1]
  4816. ]);
  4817. this.groupStack.push(currentCtx);
  4818. this.groupLevel++;
  4819. },
  4820. endGroup: function CanvasGraphics_endGroup(group) {
  4821. this.groupLevel--;
  4822. var groupCtx = this.ctx;
  4823. this.ctx = this.groupStack.pop();
  4824. // Turn off image smoothing to avoid sub pixel interpolation which can
  4825. // look kind of blurry for some pdfs.
  4826. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4827. this.ctx.imageSmoothingEnabled = false;
  4828. } else {
  4829. this.ctx.mozImageSmoothingEnabled = false;
  4830. }
  4831. if (group.smask) {
  4832. this.tempSMask = this.smaskStack.pop();
  4833. } else {
  4834. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4835. }
  4836. this.restore();
  4837. },
  4838. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4839. this.save();
  4840. this.current = new CanvasExtraState();
  4841. },
  4842. endAnnotations: function CanvasGraphics_endAnnotations() {
  4843. this.restore();
  4844. },
  4845. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4846. matrix) {
  4847. this.save();
  4848. if (isArray(rect) && 4 === rect.length) {
  4849. var width = rect[2] - rect[0];
  4850. var height = rect[3] - rect[1];
  4851. this.rectangle(rect[0], rect[1], width, height);
  4852. this.clip();
  4853. this.endPath();
  4854. }
  4855. this.transform.apply(this, transform);
  4856. this.transform.apply(this, matrix);
  4857. },
  4858. endAnnotation: function CanvasGraphics_endAnnotation() {
  4859. this.restore();
  4860. },
  4861. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4862. var domImage = this.objs.get(objId);
  4863. if (!domImage) {
  4864. warn('Dependent image isn\'t ready yet');
  4865. return;
  4866. }
  4867. this.save();
  4868. var ctx = this.ctx;
  4869. // scale the image to the unit square
  4870. ctx.scale(1 / w, -1 / h);
  4871. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4872. 0, -h, w, h);
  4873. if (this.imageLayer) {
  4874. var currentTransform = ctx.mozCurrentTransformInverse;
  4875. var position = this.getCanvasPosition(0, 0);
  4876. this.imageLayer.appendImage({
  4877. objId: objId,
  4878. left: position[0],
  4879. top: position[1],
  4880. width: w / currentTransform[0],
  4881. height: h / currentTransform[3]
  4882. });
  4883. }
  4884. this.restore();
  4885. },
  4886. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4887. var ctx = this.ctx;
  4888. var width = img.width, height = img.height;
  4889. var glyph = this.processingType3;
  4890. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  4891. var MAX_SIZE_TO_COMPILE = 1000;
  4892. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4893. glyph.compiled =
  4894. compileType3Glyph({data: img.data, width: width, height: height});
  4895. } else {
  4896. glyph.compiled = null;
  4897. }
  4898. }
  4899. if (glyph && glyph.compiled) {
  4900. glyph.compiled(ctx);
  4901. return;
  4902. }
  4903. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4904. var maskCtx = maskCanvas.context;
  4905. maskCtx.save();
  4906. putBinaryImageMask(maskCtx, img);
  4907. maskCtx.globalCompositeOperation = 'source-in';
  4908. var fillColor = this.current.fillColor;
  4909. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4910. fillColor.type === 'Pattern') ?
  4911. fillColor.getPattern(maskCtx, this) : fillColor;
  4912. maskCtx.fillRect(0, 0, width, height);
  4913. maskCtx.restore();
  4914. this.paintInlineImageXObject(maskCanvas.canvas);
  4915. },
  4916. paintImageMaskXObjectRepeat:
  4917. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4918. scaleY, positions) {
  4919. var width = imgData.width;
  4920. var height = imgData.height;
  4921. var ctx = this.ctx;
  4922. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4923. var maskCtx = maskCanvas.context;
  4924. maskCtx.save();
  4925. putBinaryImageMask(maskCtx, imgData);
  4926. maskCtx.globalCompositeOperation = 'source-in';
  4927. var fillColor = this.current.fillColor;
  4928. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4929. fillColor.type === 'Pattern') ?
  4930. fillColor.getPattern(maskCtx, this) : fillColor;
  4931. maskCtx.fillRect(0, 0, width, height);
  4932. maskCtx.restore();
  4933. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4934. ctx.save();
  4935. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4936. ctx.scale(1, -1);
  4937. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4938. 0, -1, 1, 1);
  4939. ctx.restore();
  4940. }
  4941. },
  4942. paintImageMaskXObjectGroup:
  4943. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4944. var ctx = this.ctx;
  4945. for (var i = 0, ii = images.length; i < ii; i++) {
  4946. var image = images[i];
  4947. var width = image.width, height = image.height;
  4948. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4949. var maskCtx = maskCanvas.context;
  4950. maskCtx.save();
  4951. putBinaryImageMask(maskCtx, image);
  4952. maskCtx.globalCompositeOperation = 'source-in';
  4953. var fillColor = this.current.fillColor;
  4954. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4955. fillColor.type === 'Pattern') ?
  4956. fillColor.getPattern(maskCtx, this) : fillColor;
  4957. maskCtx.fillRect(0, 0, width, height);
  4958. maskCtx.restore();
  4959. ctx.save();
  4960. ctx.transform.apply(ctx, image.transform);
  4961. ctx.scale(1, -1);
  4962. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4963. 0, -1, 1, 1);
  4964. ctx.restore();
  4965. }
  4966. },
  4967. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4968. var imgData = this.objs.get(objId);
  4969. if (!imgData) {
  4970. warn('Dependent image isn\'t ready yet');
  4971. return;
  4972. }
  4973. this.paintInlineImageXObject(imgData);
  4974. },
  4975. paintImageXObjectRepeat:
  4976. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4977. positions) {
  4978. var imgData = this.objs.get(objId);
  4979. if (!imgData) {
  4980. warn('Dependent image isn\'t ready yet');
  4981. return;
  4982. }
  4983. var width = imgData.width;
  4984. var height = imgData.height;
  4985. var map = [];
  4986. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4987. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4988. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4989. }
  4990. this.paintInlineImageXObjectGroup(imgData, map);
  4991. },
  4992. paintInlineImageXObject:
  4993. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4994. var width = imgData.width;
  4995. var height = imgData.height;
  4996. var ctx = this.ctx;
  4997. this.save();
  4998. // scale the image to the unit square
  4999. ctx.scale(1 / width, -1 / height);
  5000. var currentTransform = ctx.mozCurrentTransformInverse;
  5001. var a = currentTransform[0], b = currentTransform[1];
  5002. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  5003. var c = currentTransform[2], d = currentTransform[3];
  5004. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  5005. var imgToPaint, tmpCanvas;
  5006. // instanceof HTMLElement does not work in jsdom node.js module
  5007. if (imgData instanceof HTMLElement || !imgData.data) {
  5008. imgToPaint = imgData;
  5009. } else {
  5010. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  5011. var tmpCtx = tmpCanvas.context;
  5012. putBinaryImageData(tmpCtx, imgData);
  5013. imgToPaint = tmpCanvas.canvas;
  5014. }
  5015. var paintWidth = width, paintHeight = height;
  5016. var tmpCanvasId = 'prescale1';
  5017. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  5018. // pixels during drawImage operation, painting on the temporary canvas(es)
  5019. // that are twice smaller in size
  5020. while ((widthScale > 2 && paintWidth > 1) ||
  5021. (heightScale > 2 && paintHeight > 1)) {
  5022. var newWidth = paintWidth, newHeight = paintHeight;
  5023. if (widthScale > 2 && paintWidth > 1) {
  5024. newWidth = Math.ceil(paintWidth / 2);
  5025. widthScale /= paintWidth / newWidth;
  5026. }
  5027. if (heightScale > 2 && paintHeight > 1) {
  5028. newHeight = Math.ceil(paintHeight / 2);
  5029. heightScale /= paintHeight / newHeight;
  5030. }
  5031. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5032. tmpCtx = tmpCanvas.context;
  5033. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5034. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  5035. 0, 0, newWidth, newHeight);
  5036. imgToPaint = tmpCanvas.canvas;
  5037. paintWidth = newWidth;
  5038. paintHeight = newHeight;
  5039. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  5040. }
  5041. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  5042. 0, -height, width, height);
  5043. if (this.imageLayer) {
  5044. var position = this.getCanvasPosition(0, -height);
  5045. this.imageLayer.appendImage({
  5046. imgData: imgData,
  5047. left: position[0],
  5048. top: position[1],
  5049. width: width / currentTransform[0],
  5050. height: height / currentTransform[3]
  5051. });
  5052. }
  5053. this.restore();
  5054. },
  5055. paintInlineImageXObjectGroup:
  5056. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  5057. var ctx = this.ctx;
  5058. var w = imgData.width;
  5059. var h = imgData.height;
  5060. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  5061. var tmpCtx = tmpCanvas.context;
  5062. putBinaryImageData(tmpCtx, imgData);
  5063. for (var i = 0, ii = map.length; i < ii; i++) {
  5064. var entry = map[i];
  5065. ctx.save();
  5066. ctx.transform.apply(ctx, entry.transform);
  5067. ctx.scale(1, -1);
  5068. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  5069. 0, -1, 1, 1);
  5070. if (this.imageLayer) {
  5071. var position = this.getCanvasPosition(entry.x, entry.y);
  5072. this.imageLayer.appendImage({
  5073. imgData: imgData,
  5074. left: position[0],
  5075. top: position[1],
  5076. width: w,
  5077. height: h
  5078. });
  5079. }
  5080. ctx.restore();
  5081. }
  5082. },
  5083. paintSolidColorImageMask:
  5084. function CanvasGraphics_paintSolidColorImageMask() {
  5085. this.ctx.fillRect(0, 0, 1, 1);
  5086. },
  5087. // Marked content
  5088. markPoint: function CanvasGraphics_markPoint(tag) {
  5089. // TODO Marked content.
  5090. },
  5091. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  5092. // TODO Marked content.
  5093. },
  5094. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  5095. // TODO Marked content.
  5096. },
  5097. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  5098. tag, properties) {
  5099. // TODO Marked content.
  5100. },
  5101. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  5102. // TODO Marked content.
  5103. },
  5104. // Compatibility
  5105. beginCompat: function CanvasGraphics_beginCompat() {
  5106. // TODO ignore undefined operators (should we do that anyway?)
  5107. },
  5108. endCompat: function CanvasGraphics_endCompat() {
  5109. // TODO stop ignoring undefined operators
  5110. },
  5111. // Helper functions
  5112. consumePath: function CanvasGraphics_consumePath() {
  5113. var ctx = this.ctx;
  5114. if (this.pendingClip) {
  5115. if (this.pendingClip === EO_CLIP) {
  5116. if (ctx.mozFillRule !== undefined) {
  5117. ctx.mozFillRule = 'evenodd';
  5118. ctx.clip();
  5119. ctx.mozFillRule = 'nonzero';
  5120. } else {
  5121. try {
  5122. ctx.clip('evenodd');
  5123. } catch (ex) {
  5124. // shouldn't really happen, but browsers might think differently
  5125. ctx.clip();
  5126. }
  5127. }
  5128. } else {
  5129. ctx.clip();
  5130. }
  5131. this.pendingClip = null;
  5132. }
  5133. ctx.beginPath();
  5134. },
  5135. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  5136. var inverse = this.ctx.mozCurrentTransformInverse;
  5137. // max of the current horizontal and vertical scale
  5138. return Math.sqrt(Math.max(
  5139. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  5140. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  5141. },
  5142. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  5143. var transform = this.ctx.mozCurrentTransform;
  5144. return [
  5145. transform[0] * x + transform[2] * y + transform[4],
  5146. transform[1] * x + transform[3] * y + transform[5]
  5147. ];
  5148. }
  5149. };
  5150. for (var op in OPS) {
  5151. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  5152. }
  5153. return CanvasGraphics;
  5154. })();
  5155. var WebGLUtils = (function WebGLUtilsClosure() {
  5156. function loadShader(gl, code, shaderType) {
  5157. var shader = gl.createShader(shaderType);
  5158. gl.shaderSource(shader, code);
  5159. gl.compileShader(shader);
  5160. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5161. if (!compiled) {
  5162. var errorMsg = gl.getShaderInfoLog(shader);
  5163. throw new Error('Error during shader compilation: ' + errorMsg);
  5164. }
  5165. return shader;
  5166. }
  5167. function createVertexShader(gl, code) {
  5168. return loadShader(gl, code, gl.VERTEX_SHADER);
  5169. }
  5170. function createFragmentShader(gl, code) {
  5171. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5172. }
  5173. function createProgram(gl, shaders) {
  5174. var program = gl.createProgram();
  5175. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5176. gl.attachShader(program, shaders[i]);
  5177. }
  5178. gl.linkProgram(program);
  5179. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5180. if (!linked) {
  5181. var errorMsg = gl.getProgramInfoLog(program);
  5182. throw new Error('Error during program linking: ' + errorMsg);
  5183. }
  5184. return program;
  5185. }
  5186. function createTexture(gl, image, textureId) {
  5187. gl.activeTexture(textureId);
  5188. var texture = gl.createTexture();
  5189. gl.bindTexture(gl.TEXTURE_2D, texture);
  5190. // Set the parameters so we can render any size image.
  5191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5195. // Upload the image into the texture.
  5196. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5197. return texture;
  5198. }
  5199. var currentGL, currentCanvas;
  5200. function generageGL() {
  5201. if (currentGL) {
  5202. return;
  5203. }
  5204. currentCanvas = document.createElement('canvas');
  5205. currentGL = currentCanvas.getContext('webgl',
  5206. { premultipliedalpha: false });
  5207. }
  5208. var smaskVertexShaderCode = '\
  5209. attribute vec2 a_position; \
  5210. attribute vec2 a_texCoord; \
  5211. \
  5212. uniform vec2 u_resolution; \
  5213. \
  5214. varying vec2 v_texCoord; \
  5215. \
  5216. void main() { \
  5217. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5218. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5219. \
  5220. v_texCoord = a_texCoord; \
  5221. } ';
  5222. var smaskFragmentShaderCode = '\
  5223. precision mediump float; \
  5224. \
  5225. uniform vec4 u_backdrop; \
  5226. uniform int u_subtype; \
  5227. uniform sampler2D u_image; \
  5228. uniform sampler2D u_mask; \
  5229. \
  5230. varying vec2 v_texCoord; \
  5231. \
  5232. void main() { \
  5233. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5234. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5235. if (u_backdrop.a > 0.0) { \
  5236. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5237. u_backdrop.rgb * (1.0 - maskColor.a); \
  5238. } \
  5239. float lum; \
  5240. if (u_subtype == 0) { \
  5241. lum = maskColor.a; \
  5242. } else { \
  5243. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5244. maskColor.b * 0.11; \
  5245. } \
  5246. imageColor.a *= lum; \
  5247. imageColor.rgb *= imageColor.a; \
  5248. gl_FragColor = imageColor; \
  5249. } ';
  5250. var smaskCache = null;
  5251. function initSmaskGL() {
  5252. var canvas, gl;
  5253. generageGL();
  5254. canvas = currentCanvas;
  5255. currentCanvas = null;
  5256. gl = currentGL;
  5257. currentGL = null;
  5258. // setup a GLSL program
  5259. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5260. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5261. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5262. gl.useProgram(program);
  5263. var cache = {};
  5264. cache.gl = gl;
  5265. cache.canvas = canvas;
  5266. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5267. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5268. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5269. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5270. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5271. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5272. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5273. // provide texture coordinates for the rectangle.
  5274. var texCoordBuffer = gl.createBuffer();
  5275. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5276. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5277. 0.0, 0.0,
  5278. 1.0, 0.0,
  5279. 0.0, 1.0,
  5280. 0.0, 1.0,
  5281. 1.0, 0.0,
  5282. 1.0, 1.0]), gl.STATIC_DRAW);
  5283. gl.enableVertexAttribArray(texCoordLocation);
  5284. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5285. gl.uniform1i(texLayerLocation, 0);
  5286. gl.uniform1i(texMaskLocation, 1);
  5287. smaskCache = cache;
  5288. }
  5289. function composeSMask(layer, mask, properties) {
  5290. var width = layer.width, height = layer.height;
  5291. if (!smaskCache) {
  5292. initSmaskGL();
  5293. }
  5294. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5295. canvas.width = width;
  5296. canvas.height = height;
  5297. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5298. gl.uniform2f(cache.resolutionLocation, width, height);
  5299. if (properties.backdrop) {
  5300. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5301. properties.backdrop[1], properties.backdrop[2], 1);
  5302. } else {
  5303. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5304. }
  5305. gl.uniform1i(cache.subtypeLocation,
  5306. properties.subtype === 'Luminosity' ? 1 : 0);
  5307. // Create a textures
  5308. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5309. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5310. // Create a buffer and put a single clipspace rectangle in
  5311. // it (2 triangles)
  5312. var buffer = gl.createBuffer();
  5313. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5314. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5315. 0, 0,
  5316. width, 0,
  5317. 0, height,
  5318. 0, height,
  5319. width, 0,
  5320. width, height]), gl.STATIC_DRAW);
  5321. gl.enableVertexAttribArray(cache.positionLocation);
  5322. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5323. // draw
  5324. gl.clearColor(0, 0, 0, 0);
  5325. gl.enable(gl.BLEND);
  5326. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5327. gl.clear(gl.COLOR_BUFFER_BIT);
  5328. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5329. gl.flush();
  5330. gl.deleteTexture(texture);
  5331. gl.deleteTexture(maskTexture);
  5332. gl.deleteBuffer(buffer);
  5333. return canvas;
  5334. }
  5335. var figuresVertexShaderCode = '\
  5336. attribute vec2 a_position; \
  5337. attribute vec3 a_color; \
  5338. \
  5339. uniform vec2 u_resolution; \
  5340. uniform vec2 u_scale; \
  5341. uniform vec2 u_offset; \
  5342. \
  5343. varying vec4 v_color; \
  5344. \
  5345. void main() { \
  5346. vec2 position = (a_position + u_offset) * u_scale; \
  5347. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5348. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5349. \
  5350. v_color = vec4(a_color / 255.0, 1.0); \
  5351. } ';
  5352. var figuresFragmentShaderCode = '\
  5353. precision mediump float; \
  5354. \
  5355. varying vec4 v_color; \
  5356. \
  5357. void main() { \
  5358. gl_FragColor = v_color; \
  5359. } ';
  5360. var figuresCache = null;
  5361. function initFiguresGL() {
  5362. var canvas, gl;
  5363. generageGL();
  5364. canvas = currentCanvas;
  5365. currentCanvas = null;
  5366. gl = currentGL;
  5367. currentGL = null;
  5368. // setup a GLSL program
  5369. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5370. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5371. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5372. gl.useProgram(program);
  5373. var cache = {};
  5374. cache.gl = gl;
  5375. cache.canvas = canvas;
  5376. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5377. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5378. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5379. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5380. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5381. figuresCache = cache;
  5382. }
  5383. function drawFigures(width, height, backgroundColor, figures, context) {
  5384. if (!figuresCache) {
  5385. initFiguresGL();
  5386. }
  5387. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5388. canvas.width = width;
  5389. canvas.height = height;
  5390. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5391. gl.uniform2f(cache.resolutionLocation, width, height);
  5392. // count triangle points
  5393. var count = 0;
  5394. var i, ii, rows;
  5395. for (i = 0, ii = figures.length; i < ii; i++) {
  5396. switch (figures[i].type) {
  5397. case 'lattice':
  5398. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5399. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5400. break;
  5401. case 'triangles':
  5402. count += figures[i].coords.length;
  5403. break;
  5404. }
  5405. }
  5406. // transfer data
  5407. var coords = new Float32Array(count * 2);
  5408. var colors = new Uint8Array(count * 3);
  5409. var coordsMap = context.coords, colorsMap = context.colors;
  5410. var pIndex = 0, cIndex = 0;
  5411. for (i = 0, ii = figures.length; i < ii; i++) {
  5412. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5413. switch (figure.type) {
  5414. case 'lattice':
  5415. var cols = figure.verticesPerRow;
  5416. rows = (ps.length / cols) | 0;
  5417. for (var row = 1; row < rows; row++) {
  5418. var offset = row * cols + 1;
  5419. for (var col = 1; col < cols; col++, offset++) {
  5420. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5421. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5422. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5423. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5424. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5425. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5426. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5427. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5428. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5429. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5430. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5431. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5432. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5433. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5434. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5435. coords[pIndex + 6] = coords[pIndex + 2];
  5436. coords[pIndex + 7] = coords[pIndex + 3];
  5437. coords[pIndex + 8] = coords[pIndex + 4];
  5438. coords[pIndex + 9] = coords[pIndex + 5];
  5439. coords[pIndex + 10] = coordsMap[ps[offset]];
  5440. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5441. colors[cIndex + 9] = colors[cIndex + 3];
  5442. colors[cIndex + 10] = colors[cIndex + 4];
  5443. colors[cIndex + 11] = colors[cIndex + 5];
  5444. colors[cIndex + 12] = colors[cIndex + 6];
  5445. colors[cIndex + 13] = colors[cIndex + 7];
  5446. colors[cIndex + 14] = colors[cIndex + 8];
  5447. colors[cIndex + 15] = colorsMap[cs[offset]];
  5448. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5449. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5450. pIndex += 12;
  5451. cIndex += 18;
  5452. }
  5453. }
  5454. break;
  5455. case 'triangles':
  5456. for (var j = 0, jj = ps.length; j < jj; j++) {
  5457. coords[pIndex] = coordsMap[ps[j]];
  5458. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5459. colors[cIndex] = colorsMap[cs[i]];
  5460. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5461. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5462. pIndex += 2;
  5463. cIndex += 3;
  5464. }
  5465. break;
  5466. }
  5467. }
  5468. // draw
  5469. if (backgroundColor) {
  5470. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5471. backgroundColor[2] / 255, 1.0);
  5472. } else {
  5473. gl.clearColor(0, 0, 0, 0);
  5474. }
  5475. gl.clear(gl.COLOR_BUFFER_BIT);
  5476. var coordsBuffer = gl.createBuffer();
  5477. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5478. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5479. gl.enableVertexAttribArray(cache.positionLocation);
  5480. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5481. var colorsBuffer = gl.createBuffer();
  5482. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5483. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5484. gl.enableVertexAttribArray(cache.colorLocation);
  5485. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5486. 0, 0);
  5487. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5488. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5489. gl.drawArrays(gl.TRIANGLES, 0, count);
  5490. gl.flush();
  5491. gl.deleteBuffer(coordsBuffer);
  5492. gl.deleteBuffer(colorsBuffer);
  5493. return canvas;
  5494. }
  5495. function cleanup() {
  5496. smaskCache = null;
  5497. figuresCache = null;
  5498. }
  5499. return {
  5500. get isEnabled() {
  5501. if (PDFJS.disableWebGL) {
  5502. return false;
  5503. }
  5504. var enabled = false;
  5505. try {
  5506. generageGL();
  5507. enabled = !!currentGL;
  5508. } catch (e) { }
  5509. return shadow(this, 'isEnabled', enabled);
  5510. },
  5511. composeSMask: composeSMask,
  5512. drawFigures: drawFigures,
  5513. clear: cleanup
  5514. };
  5515. })();
  5516. var ShadingIRs = {};
  5517. ShadingIRs.RadialAxial = {
  5518. fromIR: function RadialAxial_fromIR(raw) {
  5519. var type = raw[1];
  5520. var colorStops = raw[2];
  5521. var p0 = raw[3];
  5522. var p1 = raw[4];
  5523. var r0 = raw[5];
  5524. var r1 = raw[6];
  5525. return {
  5526. type: 'Pattern',
  5527. getPattern: function RadialAxial_getPattern(ctx) {
  5528. var grad;
  5529. if (type === 'axial') {
  5530. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5531. } else if (type === 'radial') {
  5532. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5533. }
  5534. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5535. var c = colorStops[i];
  5536. grad.addColorStop(c[0], c[1]);
  5537. }
  5538. return grad;
  5539. }
  5540. };
  5541. }
  5542. };
  5543. var createMeshCanvas = (function createMeshCanvasClosure() {
  5544. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5545. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5546. var coords = context.coords, colors = context.colors;
  5547. var bytes = data.data, rowSize = data.width * 4;
  5548. var tmp;
  5549. if (coords[p1 + 1] > coords[p2 + 1]) {
  5550. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5551. }
  5552. if (coords[p2 + 1] > coords[p3 + 1]) {
  5553. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5554. }
  5555. if (coords[p1 + 1] > coords[p2 + 1]) {
  5556. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5557. }
  5558. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5559. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5560. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5561. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5562. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5563. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5564. if (y1 >= y3) {
  5565. return;
  5566. }
  5567. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5568. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5569. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5570. var minY = Math.round(y1), maxY = Math.round(y3);
  5571. var xa, car, cag, cab;
  5572. var xb, cbr, cbg, cbb;
  5573. var k;
  5574. for (var y = minY; y <= maxY; y++) {
  5575. if (y < y2) {
  5576. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5577. xa = x1 - (x1 - x2) * k;
  5578. car = c1r - (c1r - c2r) * k;
  5579. cag = c1g - (c1g - c2g) * k;
  5580. cab = c1b - (c1b - c2b) * k;
  5581. } else {
  5582. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5583. xa = x2 - (x2 - x3) * k;
  5584. car = c2r - (c2r - c3r) * k;
  5585. cag = c2g - (c2g - c3g) * k;
  5586. cab = c2b - (c2b - c3b) * k;
  5587. }
  5588. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5589. xb = x1 - (x1 - x3) * k;
  5590. cbr = c1r - (c1r - c3r) * k;
  5591. cbg = c1g - (c1g - c3g) * k;
  5592. cbb = c1b - (c1b - c3b) * k;
  5593. var x1_ = Math.round(Math.min(xa, xb));
  5594. var x2_ = Math.round(Math.max(xa, xb));
  5595. var j = rowSize * y + x1_ * 4;
  5596. for (var x = x1_; x <= x2_; x++) {
  5597. k = (xa - x) / (xa - xb);
  5598. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5599. bytes[j++] = (car - (car - cbr) * k) | 0;
  5600. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5601. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5602. bytes[j++] = 255;
  5603. }
  5604. }
  5605. }
  5606. function drawFigure(data, figure, context) {
  5607. var ps = figure.coords;
  5608. var cs = figure.colors;
  5609. var i, ii;
  5610. switch (figure.type) {
  5611. case 'lattice':
  5612. var verticesPerRow = figure.verticesPerRow;
  5613. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5614. var cols = verticesPerRow - 1;
  5615. for (i = 0; i < rows; i++) {
  5616. var q = i * verticesPerRow;
  5617. for (var j = 0; j < cols; j++, q++) {
  5618. drawTriangle(data, context,
  5619. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5620. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5621. drawTriangle(data, context,
  5622. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5623. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5624. }
  5625. }
  5626. break;
  5627. case 'triangles':
  5628. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5629. drawTriangle(data, context,
  5630. ps[i], ps[i + 1], ps[i + 2],
  5631. cs[i], cs[i + 1], cs[i + 2]);
  5632. }
  5633. break;
  5634. default:
  5635. error('illigal figure');
  5636. break;
  5637. }
  5638. }
  5639. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5640. backgroundColor) {
  5641. // we will increase scale on some weird factor to let antialiasing take
  5642. // care of "rough" edges
  5643. var EXPECTED_SCALE = 1.1;
  5644. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5645. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5646. var offsetX = Math.floor(bounds[0]);
  5647. var offsetY = Math.floor(bounds[1]);
  5648. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5649. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5650. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5651. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5652. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5653. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5654. var scaleX = boundsWidth / width;
  5655. var scaleY = boundsHeight / height;
  5656. var context = {
  5657. coords: coords,
  5658. colors: colors,
  5659. offsetX: -offsetX,
  5660. offsetY: -offsetY,
  5661. scaleX: 1 / scaleX,
  5662. scaleY: 1 / scaleY
  5663. };
  5664. var canvas, tmpCanvas, i, ii;
  5665. if (WebGLUtils.isEnabled) {
  5666. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5667. figures, context);
  5668. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5669. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5670. tmpCanvas.context.drawImage(canvas, 0, 0);
  5671. canvas = tmpCanvas.canvas;
  5672. } else {
  5673. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5674. var tmpCtx = tmpCanvas.context;
  5675. var data = tmpCtx.createImageData(width, height);
  5676. if (backgroundColor) {
  5677. var bytes = data.data;
  5678. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5679. bytes[i] = backgroundColor[0];
  5680. bytes[i + 1] = backgroundColor[1];
  5681. bytes[i + 2] = backgroundColor[2];
  5682. bytes[i + 3] = 255;
  5683. }
  5684. }
  5685. for (i = 0; i < figures.length; i++) {
  5686. drawFigure(data, figures[i], context);
  5687. }
  5688. tmpCtx.putImageData(data, 0, 0);
  5689. canvas = tmpCanvas.canvas;
  5690. }
  5691. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5692. scaleX: scaleX, scaleY: scaleY};
  5693. }
  5694. return createMeshCanvas;
  5695. })();
  5696. ShadingIRs.Mesh = {
  5697. fromIR: function Mesh_fromIR(raw) {
  5698. //var type = raw[1];
  5699. var coords = raw[2];
  5700. var colors = raw[3];
  5701. var figures = raw[4];
  5702. var bounds = raw[5];
  5703. var matrix = raw[6];
  5704. //var bbox = raw[7];
  5705. var background = raw[8];
  5706. return {
  5707. type: 'Pattern',
  5708. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5709. var combinedScale;
  5710. // Obtain scale from matrix and current transformation matrix.
  5711. if (shadingFill) {
  5712. combinedScale = Util.singularValueDecompose2dScale(
  5713. ctx.mozCurrentTransform);
  5714. } else {
  5715. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5716. var curMatrixScale = Util.singularValueDecompose2dScale(
  5717. owner.baseTransform);
  5718. combinedScale = [matrixScale[0] * curMatrixScale[0],
  5719. matrixScale[1] * curMatrixScale[1]];
  5720. }
  5721. // Rasterizing on the main thread since sending/queue large canvases
  5722. // might cause OOM.
  5723. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,
  5724. coords, colors, figures, shadingFill ? null : background);
  5725. if (!shadingFill) {
  5726. ctx.setTransform.apply(ctx, owner.baseTransform);
  5727. if (matrix) {
  5728. ctx.transform.apply(ctx, matrix);
  5729. }
  5730. }
  5731. ctx.translate(temporaryPatternCanvas.offsetX,
  5732. temporaryPatternCanvas.offsetY);
  5733. ctx.scale(temporaryPatternCanvas.scaleX,
  5734. temporaryPatternCanvas.scaleY);
  5735. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5736. }
  5737. };
  5738. }
  5739. };
  5740. ShadingIRs.Dummy = {
  5741. fromIR: function Dummy_fromIR() {
  5742. return {
  5743. type: 'Pattern',
  5744. getPattern: function Dummy_fromIR_getPattern() {
  5745. return 'hotpink';
  5746. }
  5747. };
  5748. }
  5749. };
  5750. function getShadingPatternFromIR(raw) {
  5751. var shadingIR = ShadingIRs[raw[0]];
  5752. if (!shadingIR) {
  5753. error('Unknown IR type: ' + raw[0]);
  5754. }
  5755. return shadingIR.fromIR(raw);
  5756. }
  5757. var TilingPattern = (function TilingPatternClosure() {
  5758. var PaintType = {
  5759. COLORED: 1,
  5760. UNCOLORED: 2
  5761. };
  5762. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5763. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5764. this.operatorList = IR[2];
  5765. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5766. this.bbox = IR[4];
  5767. this.xstep = IR[5];
  5768. this.ystep = IR[6];
  5769. this.paintType = IR[7];
  5770. this.tilingType = IR[8];
  5771. this.color = color;
  5772. this.objs = objs;
  5773. this.commonObjs = commonObjs;
  5774. this.baseTransform = baseTransform;
  5775. this.type = 'Pattern';
  5776. this.ctx = ctx;
  5777. }
  5778. TilingPattern.prototype = {
  5779. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5780. var operatorList = this.operatorList;
  5781. var bbox = this.bbox;
  5782. var xstep = this.xstep;
  5783. var ystep = this.ystep;
  5784. var paintType = this.paintType;
  5785. var tilingType = this.tilingType;
  5786. var color = this.color;
  5787. var objs = this.objs;
  5788. var commonObjs = this.commonObjs;
  5789. info('TilingType: ' + tilingType);
  5790. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5791. var topLeft = [x0, y0];
  5792. // we want the canvas to be as large as the step size
  5793. var botRight = [x0 + xstep, y0 + ystep];
  5794. var width = botRight[0] - topLeft[0];
  5795. var height = botRight[1] - topLeft[1];
  5796. // Obtain scale from matrix and current transformation matrix.
  5797. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5798. var curMatrixScale = Util.singularValueDecompose2dScale(
  5799. this.baseTransform);
  5800. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5801. matrixScale[1] * curMatrixScale[1]];
  5802. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5803. // Use width and height values that are as close as possible to the end
  5804. // result when the pattern is used. Too low value makes the pattern look
  5805. // blurry. Too large value makes it look too crispy.
  5806. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5807. MAX_PATTERN_SIZE);
  5808. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5809. MAX_PATTERN_SIZE);
  5810. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5811. var tmpCtx = tmpCanvas.context;
  5812. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5813. graphics.groupLevel = owner.groupLevel;
  5814. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5815. this.setScale(width, height, xstep, ystep);
  5816. this.transformToScale(graphics);
  5817. // transform coordinates to pattern space
  5818. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5819. graphics.transform.apply(graphics, tmpTranslate);
  5820. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5821. graphics.executeOperatorList(operatorList);
  5822. return tmpCanvas.canvas;
  5823. },
  5824. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5825. this.scale = [width / xstep, height / ystep];
  5826. },
  5827. transformToScale: function TilingPattern_transformToScale(graphics) {
  5828. var scale = this.scale;
  5829. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5830. graphics.transform.apply(graphics, tmpScale);
  5831. },
  5832. scaleToContext: function TilingPattern_scaleToContext() {
  5833. var scale = this.scale;
  5834. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5835. },
  5836. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5837. if (bbox && isArray(bbox) && 4 == bbox.length) {
  5838. var bboxWidth = x1 - x0;
  5839. var bboxHeight = y1 - y0;
  5840. graphics.rectangle(x0, y0, bboxWidth, bboxHeight);
  5841. graphics.clip();
  5842. graphics.endPath();
  5843. }
  5844. },
  5845. setFillAndStrokeStyleToContext:
  5846. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5847. switch (paintType) {
  5848. case PaintType.COLORED:
  5849. var ctx = this.ctx;
  5850. context.fillStyle = ctx.fillStyle;
  5851. context.strokeStyle = ctx.strokeStyle;
  5852. break;
  5853. case PaintType.UNCOLORED:
  5854. var cssColor = Util.makeCssRgb(color);
  5855. context.fillStyle = cssColor;
  5856. context.strokeStyle = cssColor;
  5857. break;
  5858. default:
  5859. error('Unsupported paint type: ' + paintType);
  5860. }
  5861. },
  5862. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5863. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5864. ctx = this.ctx;
  5865. ctx.setTransform.apply(ctx, this.baseTransform);
  5866. ctx.transform.apply(ctx, this.matrix);
  5867. this.scaleToContext();
  5868. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5869. }
  5870. };
  5871. return TilingPattern;
  5872. })();
  5873. PDFJS.disableFontFace = false;
  5874. var FontLoader = {
  5875. insertRule: function fontLoaderInsertRule(rule) {
  5876. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5877. if (!styleElement) {
  5878. styleElement = document.createElement('style');
  5879. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5880. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5881. styleElement);
  5882. }
  5883. var styleSheet = styleElement.sheet;
  5884. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5885. },
  5886. clear: function fontLoaderClear() {
  5887. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5888. if (styleElement) {
  5889. styleElement.parentNode.removeChild(styleElement);
  5890. }
  5891. },
  5892. get loadTestFont() {
  5893. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5894. // height.
  5895. return shadow(this, 'loadTestFont', atob(
  5896. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5897. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5898. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5899. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5900. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5901. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5902. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5903. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5904. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5905. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5906. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5907. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5908. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5909. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5910. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5911. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5912. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5913. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5914. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5915. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5916. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5917. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5918. ));
  5919. },
  5920. loadTestFontId: 0,
  5921. loadingContext: {
  5922. requests: [],
  5923. nextRequestId: 0
  5924. },
  5925. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5926. if (isWorker) {
  5927. return false;
  5928. }
  5929. // User agent string sniffing is bad, but there is no reliable way to tell
  5930. // if font is fully loaded and ready to be used with canvas.
  5931. var userAgent = window.navigator.userAgent;
  5932. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5933. if (m && m[1] >= 14) {
  5934. return true;
  5935. }
  5936. // TODO other browsers
  5937. return false;
  5938. })(),
  5939. bind: function fontLoaderBind(fonts, callback) {
  5940. assert(!isWorker, 'bind() shall be called from main thread');
  5941. var rules = [], fontsToLoad = [];
  5942. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5943. var font = fonts[i];
  5944. // Add the font to the DOM only once or skip if the font
  5945. // is already loaded.
  5946. if (font.attached || font.loading === false) {
  5947. continue;
  5948. }
  5949. font.attached = true;
  5950. var rule = font.bindDOM();
  5951. if (rule) {
  5952. rules.push(rule);
  5953. fontsToLoad.push(font);
  5954. }
  5955. }
  5956. var request = FontLoader.queueLoadingCallback(callback);
  5957. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5958. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5959. } else {
  5960. request.complete();
  5961. }
  5962. },
  5963. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5964. function LoadLoader_completeRequest() {
  5965. assert(!request.end, 'completeRequest() cannot be called twice');
  5966. request.end = Date.now();
  5967. // sending all completed requests in order how they were queued
  5968. while (context.requests.length > 0 && context.requests[0].end) {
  5969. var otherRequest = context.requests.shift();
  5970. setTimeout(otherRequest.callback, 0);
  5971. }
  5972. }
  5973. var context = FontLoader.loadingContext;
  5974. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5975. var request = {
  5976. id: requestId,
  5977. complete: LoadLoader_completeRequest,
  5978. callback: callback,
  5979. started: Date.now()
  5980. };
  5981. context.requests.push(request);
  5982. return request;
  5983. },
  5984. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5985. fonts,
  5986. request) {
  5987. /** Hack begin */
  5988. // There's currently no event when a font has finished downloading so the
  5989. // following code is a dirty hack to 'guess' when a font is
  5990. // ready. It's assumed fonts are loaded in order, so add a known test
  5991. // font after the desired fonts and then test for the loading of that
  5992. // test font.
  5993. function int32(data, offset) {
  5994. return (data.charCodeAt(offset) << 24) |
  5995. (data.charCodeAt(offset + 1) << 16) |
  5996. (data.charCodeAt(offset + 2) << 8) |
  5997. (data.charCodeAt(offset + 3) & 0xff);
  5998. }
  5999. function spliceString(s, offset, remove, insert) {
  6000. var chunk1 = s.substr(0, offset);
  6001. var chunk2 = s.substr(offset + remove);
  6002. return chunk1 + insert + chunk2;
  6003. }
  6004. var i, ii;
  6005. var canvas = document.createElement('canvas');
  6006. canvas.width = 1;
  6007. canvas.height = 1;
  6008. var ctx = canvas.getContext('2d');
  6009. var called = 0;
  6010. function isFontReady(name, callback) {
  6011. called++;
  6012. // With setTimeout clamping this gives the font ~100ms to load.
  6013. if(called > 30) {
  6014. warn('Load test font never loaded.');
  6015. callback();
  6016. return;
  6017. }
  6018. ctx.font = '30px ' + name;
  6019. ctx.fillText('.', 0, 20);
  6020. var imageData = ctx.getImageData(0, 0, 1, 1);
  6021. if (imageData.data[3] > 0) {
  6022. callback();
  6023. return;
  6024. }
  6025. setTimeout(isFontReady.bind(null, name, callback));
  6026. }
  6027. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  6028. // Chromium seems to cache fonts based on a hash of the actual font data,
  6029. // so the font must be modified for each load test else it will appear to
  6030. // be loaded already.
  6031. // TODO: This could maybe be made faster by avoiding the btoa of the full
  6032. // font by splitting it in chunks before hand and padding the font id.
  6033. var data = this.loadTestFont;
  6034. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  6035. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  6036. loadTestFontId);
  6037. // CFF checksum is important for IE, adjusting it
  6038. var CFF_CHECKSUM_OFFSET = 16;
  6039. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  6040. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  6041. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  6042. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  6043. }
  6044. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  6045. checksum = (checksum - XXXX_VALUE +
  6046. int32(loadTestFontId + 'XXX', i)) | 0;
  6047. }
  6048. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  6049. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  6050. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  6051. url + '}';
  6052. FontLoader.insertRule(rule);
  6053. var names = [];
  6054. for (i = 0, ii = fonts.length; i < ii; i++) {
  6055. names.push(fonts[i].loadedName);
  6056. }
  6057. names.push(loadTestFontId);
  6058. var div = document.createElement('div');
  6059. div.setAttribute('style',
  6060. 'visibility: hidden;' +
  6061. 'width: 10px; height: 10px;' +
  6062. 'position: absolute; top: 0px; left: 0px;');
  6063. for (i = 0, ii = names.length; i < ii; ++i) {
  6064. var span = document.createElement('span');
  6065. span.textContent = 'Hi';
  6066. span.style.fontFamily = names[i];
  6067. div.appendChild(span);
  6068. }
  6069. document.body.appendChild(div);
  6070. isFontReady(loadTestFontId, function() {
  6071. document.body.removeChild(div);
  6072. request.complete();
  6073. });
  6074. /** Hack end */
  6075. }
  6076. };
  6077. var FontFace = (function FontFaceClosure() {
  6078. function FontFace(name, file, properties) {
  6079. this.compiledGlyphs = {};
  6080. if (arguments.length === 1) {
  6081. // importing translated data
  6082. var data = arguments[0];
  6083. for (var i in data) {
  6084. this[i] = data[i];
  6085. }
  6086. return;
  6087. }
  6088. }
  6089. FontFace.prototype = {
  6090. bindDOM: function FontFace_bindDOM() {
  6091. if (!this.data) {
  6092. return null;
  6093. }
  6094. if (PDFJS.disableFontFace) {
  6095. this.disableFontFace = true;
  6096. return null;
  6097. }
  6098. var data = bytesToString(new Uint8Array(this.data));
  6099. var fontName = this.loadedName;
  6100. // Add the font-face rule to the document
  6101. var url = ('url(data:' + this.mimetype + ';base64,' +
  6102. window.btoa(data) + ');');
  6103. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  6104. FontLoader.insertRule(rule);
  6105. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  6106. globalScope['FontInspector'].enabled) {
  6107. globalScope['FontInspector'].fontAdded(this, url);
  6108. }
  6109. return rule;
  6110. },
  6111. getPathGenerator: function (objs, character) {
  6112. if (!(character in this.compiledGlyphs)) {
  6113. var js = objs.get(this.loadedName + '_path_' + character);
  6114. /*jshint -W054 */
  6115. this.compiledGlyphs[character] = new Function('c', 'size', js);
  6116. }
  6117. return this.compiledGlyphs[character];
  6118. }
  6119. };
  6120. return FontFace;
  6121. })();
  6122. }).call((typeof window === 'undefined') ? this : window);
  6123. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  6124. // workerSrc is not set -- using last script url to define default location
  6125. PDFJS.workerSrc = (function () {
  6126. 'use strict';
  6127. var scriptTagContainer = document.body ||
  6128. document.getElementsByTagName('head')[0];
  6129. var pdfjsSrc = scriptTagContainer.lastChild.src;
  6130. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  6131. })();
  6132. }