pdf.js 324 KB

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