pdf.js 291 KB

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