pdf.js 263 KB

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