pdf.combined.js 261 KB

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