pdf.js 331 KB

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