pdf.js 263 KB

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