pdf.js 361 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345
  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.5.434';
  30. var pdfjsBuild = '8dbb5a7';
  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.pdfjsSharedUtil = {}));
  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 FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  45. var TextRenderingMode = {
  46. FILL: 0,
  47. STROKE: 1,
  48. FILL_STROKE: 2,
  49. INVISIBLE: 3,
  50. FILL_ADD_TO_PATH: 4,
  51. STROKE_ADD_TO_PATH: 5,
  52. FILL_STROKE_ADD_TO_PATH: 6,
  53. ADD_TO_PATH: 7,
  54. FILL_STROKE_MASK: 3,
  55. ADD_TO_PATH_FLAG: 4
  56. };
  57. var ImageKind = {
  58. GRAYSCALE_1BPP: 1,
  59. RGB_24BPP: 2,
  60. RGBA_32BPP: 3
  61. };
  62. var AnnotationType = {
  63. TEXT: 1,
  64. LINK: 2,
  65. FREETEXT: 3,
  66. LINE: 4,
  67. SQUARE: 5,
  68. CIRCLE: 6,
  69. POLYGON: 7,
  70. POLYLINE: 8,
  71. HIGHLIGHT: 9,
  72. UNDERLINE: 10,
  73. SQUIGGLY: 11,
  74. STRIKEOUT: 12,
  75. STAMP: 13,
  76. CARET: 14,
  77. INK: 15,
  78. POPUP: 16,
  79. FILEATTACHMENT: 17,
  80. SOUND: 18,
  81. MOVIE: 19,
  82. WIDGET: 20,
  83. SCREEN: 21,
  84. PRINTERMARK: 22,
  85. TRAPNET: 23,
  86. WATERMARK: 24,
  87. THREED: 25,
  88. REDACT: 26
  89. };
  90. var AnnotationFlag = {
  91. INVISIBLE: 0x01,
  92. HIDDEN: 0x02,
  93. PRINT: 0x04,
  94. NOZOOM: 0x08,
  95. NOROTATE: 0x10,
  96. NOVIEW: 0x20,
  97. READONLY: 0x40,
  98. LOCKED: 0x80,
  99. TOGGLENOVIEW: 0x100,
  100. LOCKEDCONTENTS: 0x200
  101. };
  102. var AnnotationBorderStyleType = {
  103. SOLID: 1,
  104. DASHED: 2,
  105. BEVELED: 3,
  106. INSET: 4,
  107. UNDERLINE: 5
  108. };
  109. var StreamType = {
  110. UNKNOWN: 0,
  111. FLATE: 1,
  112. LZW: 2,
  113. DCT: 3,
  114. JPX: 4,
  115. JBIG: 5,
  116. A85: 6,
  117. AHX: 7,
  118. CCF: 8,
  119. RL: 9
  120. };
  121. var FontType = {
  122. UNKNOWN: 0,
  123. TYPE1: 1,
  124. TYPE1C: 2,
  125. CIDFONTTYPE0: 3,
  126. CIDFONTTYPE0C: 4,
  127. TRUETYPE: 5,
  128. CIDFONTTYPE2: 6,
  129. TYPE3: 7,
  130. OPENTYPE: 8,
  131. TYPE0: 9,
  132. MMTYPE1: 10
  133. };
  134. var VERBOSITY_LEVELS = {
  135. errors: 0,
  136. warnings: 1,
  137. infos: 5
  138. };
  139. // All the possible operations for an operator list.
  140. var OPS = {
  141. // Intentionally start from 1 so it is easy to spot bad operators that will be
  142. // 0's.
  143. dependency: 1,
  144. setLineWidth: 2,
  145. setLineCap: 3,
  146. setLineJoin: 4,
  147. setMiterLimit: 5,
  148. setDash: 6,
  149. setRenderingIntent: 7,
  150. setFlatness: 8,
  151. setGState: 9,
  152. save: 10,
  153. restore: 11,
  154. transform: 12,
  155. moveTo: 13,
  156. lineTo: 14,
  157. curveTo: 15,
  158. curveTo2: 16,
  159. curveTo3: 17,
  160. closePath: 18,
  161. rectangle: 19,
  162. stroke: 20,
  163. closeStroke: 21,
  164. fill: 22,
  165. eoFill: 23,
  166. fillStroke: 24,
  167. eoFillStroke: 25,
  168. closeFillStroke: 26,
  169. closeEOFillStroke: 27,
  170. endPath: 28,
  171. clip: 29,
  172. eoClip: 30,
  173. beginText: 31,
  174. endText: 32,
  175. setCharSpacing: 33,
  176. setWordSpacing: 34,
  177. setHScale: 35,
  178. setLeading: 36,
  179. setFont: 37,
  180. setTextRenderingMode: 38,
  181. setTextRise: 39,
  182. moveText: 40,
  183. setLeadingMoveText: 41,
  184. setTextMatrix: 42,
  185. nextLine: 43,
  186. showText: 44,
  187. showSpacedText: 45,
  188. nextLineShowText: 46,
  189. nextLineSetSpacingShowText: 47,
  190. setCharWidth: 48,
  191. setCharWidthAndBounds: 49,
  192. setStrokeColorSpace: 50,
  193. setFillColorSpace: 51,
  194. setStrokeColor: 52,
  195. setStrokeColorN: 53,
  196. setFillColor: 54,
  197. setFillColorN: 55,
  198. setStrokeGray: 56,
  199. setFillGray: 57,
  200. setStrokeRGBColor: 58,
  201. setFillRGBColor: 59,
  202. setStrokeCMYKColor: 60,
  203. setFillCMYKColor: 61,
  204. shadingFill: 62,
  205. beginInlineImage: 63,
  206. beginImageData: 64,
  207. endInlineImage: 65,
  208. paintXObject: 66,
  209. markPoint: 67,
  210. markPointProps: 68,
  211. beginMarkedContent: 69,
  212. beginMarkedContentProps: 70,
  213. endMarkedContent: 71,
  214. beginCompat: 72,
  215. endCompat: 73,
  216. paintFormXObjectBegin: 74,
  217. paintFormXObjectEnd: 75,
  218. beginGroup: 76,
  219. endGroup: 77,
  220. beginAnnotations: 78,
  221. endAnnotations: 79,
  222. beginAnnotation: 80,
  223. endAnnotation: 81,
  224. paintJpegXObject: 82,
  225. paintImageMaskXObject: 83,
  226. paintImageMaskXObjectGroup: 84,
  227. paintImageXObject: 85,
  228. paintInlineImageXObject: 86,
  229. paintInlineImageXObjectGroup: 87,
  230. paintImageXObjectRepeat: 88,
  231. paintImageMaskXObjectRepeat: 89,
  232. paintSolidColorImageMask: 90,
  233. constructPath: 91
  234. };
  235. var verbosity = VERBOSITY_LEVELS.warnings;
  236. function setVerbosityLevel(level) {
  237. verbosity = level;
  238. }
  239. function getVerbosityLevel() {
  240. return verbosity;
  241. }
  242. // A notice for devs. These are good for things that are helpful to devs, such
  243. // as warning that Workers were disabled, which is important to devs but not
  244. // end users.
  245. function info(msg) {
  246. if (verbosity >= VERBOSITY_LEVELS.infos) {
  247. console.log('Info: ' + msg);
  248. }
  249. }
  250. // Non-fatal warnings.
  251. function warn(msg) {
  252. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  253. console.log('Warning: ' + msg);
  254. }
  255. }
  256. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  257. function deprecated(details) {
  258. console.log('Deprecated API usage: ' + details);
  259. }
  260. // Fatal errors that should trigger the fallback UI and halt execution by
  261. // throwing an exception.
  262. function error(msg) {
  263. if (verbosity >= VERBOSITY_LEVELS.errors) {
  264. console.log('Error: ' + msg);
  265. console.log(backtrace());
  266. }
  267. throw new Error(msg);
  268. }
  269. function backtrace() {
  270. try {
  271. throw new Error();
  272. } catch (e) {
  273. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  274. }
  275. }
  276. function assert(cond, msg) {
  277. if (!cond) {
  278. error(msg);
  279. }
  280. }
  281. var UNSUPPORTED_FEATURES = {
  282. unknown: 'unknown',
  283. forms: 'forms',
  284. javaScript: 'javaScript',
  285. smask: 'smask',
  286. shadingPattern: 'shadingPattern',
  287. font: 'font'
  288. };
  289. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  290. function isSameOrigin(baseUrl, otherUrl) {
  291. try {
  292. var base = new URL(baseUrl);
  293. if (!base.origin || base.origin === 'null') {
  294. return false; // non-HTTP url
  295. }
  296. } catch (e) {
  297. return false;
  298. }
  299. var other = new URL(otherUrl, base);
  300. return base.origin === other.origin;
  301. }
  302. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  303. function isValidUrl(url, allowRelative) {
  304. if (!url || typeof url !== 'string') {
  305. return false;
  306. }
  307. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  308. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  309. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  310. if (!protocol) {
  311. return allowRelative;
  312. }
  313. protocol = protocol[0].toLowerCase();
  314. switch (protocol) {
  315. case 'http':
  316. case 'https':
  317. case 'ftp':
  318. case 'mailto':
  319. case 'tel':
  320. return true;
  321. default:
  322. return false;
  323. }
  324. }
  325. function shadow(obj, prop, value) {
  326. Object.defineProperty(obj, prop, { value: value,
  327. enumerable: true,
  328. configurable: true,
  329. writable: false });
  330. return value;
  331. }
  332. function getLookupTableFactory(initializer) {
  333. var lookup;
  334. return function () {
  335. if (initializer) {
  336. lookup = Object.create(null);
  337. initializer(lookup);
  338. initializer = null;
  339. }
  340. return lookup;
  341. };
  342. }
  343. var PasswordResponses = {
  344. NEED_PASSWORD: 1,
  345. INCORRECT_PASSWORD: 2
  346. };
  347. var PasswordException = (function PasswordExceptionClosure() {
  348. function PasswordException(msg, code) {
  349. this.name = 'PasswordException';
  350. this.message = msg;
  351. this.code = code;
  352. }
  353. PasswordException.prototype = new Error();
  354. PasswordException.constructor = PasswordException;
  355. return PasswordException;
  356. })();
  357. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  358. function UnknownErrorException(msg, details) {
  359. this.name = 'UnknownErrorException';
  360. this.message = msg;
  361. this.details = details;
  362. }
  363. UnknownErrorException.prototype = new Error();
  364. UnknownErrorException.constructor = UnknownErrorException;
  365. return UnknownErrorException;
  366. })();
  367. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  368. function InvalidPDFException(msg) {
  369. this.name = 'InvalidPDFException';
  370. this.message = msg;
  371. }
  372. InvalidPDFException.prototype = new Error();
  373. InvalidPDFException.constructor = InvalidPDFException;
  374. return InvalidPDFException;
  375. })();
  376. var MissingPDFException = (function MissingPDFExceptionClosure() {
  377. function MissingPDFException(msg) {
  378. this.name = 'MissingPDFException';
  379. this.message = msg;
  380. }
  381. MissingPDFException.prototype = new Error();
  382. MissingPDFException.constructor = MissingPDFException;
  383. return MissingPDFException;
  384. })();
  385. var UnexpectedResponseException =
  386. (function UnexpectedResponseExceptionClosure() {
  387. function UnexpectedResponseException(msg, status) {
  388. this.name = 'UnexpectedResponseException';
  389. this.message = msg;
  390. this.status = status;
  391. }
  392. UnexpectedResponseException.prototype = new Error();
  393. UnexpectedResponseException.constructor = UnexpectedResponseException;
  394. return UnexpectedResponseException;
  395. })();
  396. var NotImplementedException = (function NotImplementedExceptionClosure() {
  397. function NotImplementedException(msg) {
  398. this.message = msg;
  399. }
  400. NotImplementedException.prototype = new Error();
  401. NotImplementedException.prototype.name = 'NotImplementedException';
  402. NotImplementedException.constructor = NotImplementedException;
  403. return NotImplementedException;
  404. })();
  405. var MissingDataException = (function MissingDataExceptionClosure() {
  406. function MissingDataException(begin, end) {
  407. this.begin = begin;
  408. this.end = end;
  409. this.message = 'Missing data [' + begin + ', ' + end + ')';
  410. }
  411. MissingDataException.prototype = new Error();
  412. MissingDataException.prototype.name = 'MissingDataException';
  413. MissingDataException.constructor = MissingDataException;
  414. return MissingDataException;
  415. })();
  416. var XRefParseException = (function XRefParseExceptionClosure() {
  417. function XRefParseException(msg) {
  418. this.message = msg;
  419. }
  420. XRefParseException.prototype = new Error();
  421. XRefParseException.prototype.name = 'XRefParseException';
  422. XRefParseException.constructor = XRefParseException;
  423. return XRefParseException;
  424. })();
  425. var NullCharactersRegExp = /\x00/g;
  426. function removeNullCharacters(str) {
  427. if (typeof str !== 'string') {
  428. warn('The argument for removeNullCharacters must be a string.');
  429. return str;
  430. }
  431. return str.replace(NullCharactersRegExp, '');
  432. }
  433. function bytesToString(bytes) {
  434. assert(bytes !== null && typeof bytes === 'object' &&
  435. bytes.length !== undefined, 'Invalid argument for bytesToString');
  436. var length = bytes.length;
  437. var MAX_ARGUMENT_COUNT = 8192;
  438. if (length < MAX_ARGUMENT_COUNT) {
  439. return String.fromCharCode.apply(null, bytes);
  440. }
  441. var strBuf = [];
  442. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  443. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  444. var chunk = bytes.subarray(i, chunkEnd);
  445. strBuf.push(String.fromCharCode.apply(null, chunk));
  446. }
  447. return strBuf.join('');
  448. }
  449. function stringToBytes(str) {
  450. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  451. var length = str.length;
  452. var bytes = new Uint8Array(length);
  453. for (var i = 0; i < length; ++i) {
  454. bytes[i] = str.charCodeAt(i) & 0xFF;
  455. }
  456. return bytes;
  457. }
  458. /**
  459. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  460. * @param {Array|Uint8Array|string} arr
  461. * @returns {number}
  462. */
  463. function arrayByteLength(arr) {
  464. if (arr.length !== undefined) {
  465. return arr.length;
  466. }
  467. assert(arr.byteLength !== undefined);
  468. return arr.byteLength;
  469. }
  470. /**
  471. * Combines array items (arrays) into single Uint8Array object.
  472. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  473. * @returns {Uint8Array}
  474. */
  475. function arraysToBytes(arr) {
  476. // Shortcut: if first and only item is Uint8Array, return it.
  477. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) {
  478. return arr[0];
  479. }
  480. var resultLength = 0;
  481. var i, ii = arr.length;
  482. var item, itemLength ;
  483. for (i = 0; i < ii; i++) {
  484. item = arr[i];
  485. itemLength = arrayByteLength(item);
  486. resultLength += itemLength;
  487. }
  488. var pos = 0;
  489. var data = new Uint8Array(resultLength);
  490. for (i = 0; i < ii; i++) {
  491. item = arr[i];
  492. if (!(item instanceof Uint8Array)) {
  493. if (typeof item === 'string') {
  494. item = stringToBytes(item);
  495. } else {
  496. item = new Uint8Array(item);
  497. }
  498. }
  499. itemLength = item.byteLength;
  500. data.set(item, pos);
  501. pos += itemLength;
  502. }
  503. return data;
  504. }
  505. function string32(value) {
  506. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  507. (value >> 8) & 0xff, value & 0xff);
  508. }
  509. function log2(x) {
  510. var n = 1, i = 0;
  511. while (x > n) {
  512. n <<= 1;
  513. i++;
  514. }
  515. return i;
  516. }
  517. function readInt8(data, start) {
  518. return (data[start] << 24) >> 24;
  519. }
  520. function readUint16(data, offset) {
  521. return (data[offset] << 8) | data[offset + 1];
  522. }
  523. function readUint32(data, offset) {
  524. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  525. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  526. }
  527. // Lazy test the endianness of the platform
  528. // NOTE: This will be 'true' for simulated TypedArrays
  529. function isLittleEndian() {
  530. var buffer8 = new Uint8Array(2);
  531. buffer8[0] = 1;
  532. var buffer16 = new Uint16Array(buffer8.buffer);
  533. return (buffer16[0] === 1);
  534. }
  535. // Checks if it's possible to eval JS expressions.
  536. function isEvalSupported() {
  537. try {
  538. /* jshint evil: true */
  539. new Function('');
  540. return true;
  541. } catch (e) {
  542. return false;
  543. }
  544. }
  545. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  546. function Uint32ArrayView(buffer, length) {
  547. this.buffer = buffer;
  548. this.byteLength = buffer.length;
  549. this.length = length === undefined ? (this.byteLength >> 2) : length;
  550. ensureUint32ArrayViewProps(this.length);
  551. }
  552. Uint32ArrayView.prototype = Object.create(null);
  553. var uint32ArrayViewSetters = 0;
  554. function createUint32ArrayProp(index) {
  555. return {
  556. get: function () {
  557. var buffer = this.buffer, offset = index << 2;
  558. return (buffer[offset] | (buffer[offset + 1] << 8) |
  559. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  560. },
  561. set: function (value) {
  562. var buffer = this.buffer, offset = index << 2;
  563. buffer[offset] = value & 255;
  564. buffer[offset + 1] = (value >> 8) & 255;
  565. buffer[offset + 2] = (value >> 16) & 255;
  566. buffer[offset + 3] = (value >>> 24) & 255;
  567. }
  568. };
  569. }
  570. function ensureUint32ArrayViewProps(length) {
  571. while (uint32ArrayViewSetters < length) {
  572. Object.defineProperty(Uint32ArrayView.prototype,
  573. uint32ArrayViewSetters,
  574. createUint32ArrayProp(uint32ArrayViewSetters));
  575. uint32ArrayViewSetters++;
  576. }
  577. }
  578. return Uint32ArrayView;
  579. })();
  580. exports.Uint32ArrayView = Uint32ArrayView;
  581. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  582. var Util = (function UtilClosure() {
  583. function Util() {}
  584. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  585. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  586. // creating many intermediate strings.
  587. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  588. rgbBuf[1] = r;
  589. rgbBuf[3] = g;
  590. rgbBuf[5] = b;
  591. return rgbBuf.join('');
  592. };
  593. // Concatenates two transformation matrices together and returns the result.
  594. Util.transform = function Util_transform(m1, m2) {
  595. return [
  596. m1[0] * m2[0] + m1[2] * m2[1],
  597. m1[1] * m2[0] + m1[3] * m2[1],
  598. m1[0] * m2[2] + m1[2] * m2[3],
  599. m1[1] * m2[2] + m1[3] * m2[3],
  600. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  601. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  602. ];
  603. };
  604. // For 2d affine transforms
  605. Util.applyTransform = function Util_applyTransform(p, m) {
  606. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  607. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  608. return [xt, yt];
  609. };
  610. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  611. var d = m[0] * m[3] - m[1] * m[2];
  612. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  613. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  614. return [xt, yt];
  615. };
  616. // Applies the transform to the rectangle and finds the minimum axially
  617. // aligned bounding box.
  618. Util.getAxialAlignedBoundingBox =
  619. function Util_getAxialAlignedBoundingBox(r, m) {
  620. var p1 = Util.applyTransform(r, m);
  621. var p2 = Util.applyTransform(r.slice(2, 4), m);
  622. var p3 = Util.applyTransform([r[0], r[3]], m);
  623. var p4 = Util.applyTransform([r[2], r[1]], m);
  624. return [
  625. Math.min(p1[0], p2[0], p3[0], p4[0]),
  626. Math.min(p1[1], p2[1], p3[1], p4[1]),
  627. Math.max(p1[0], p2[0], p3[0], p4[0]),
  628. Math.max(p1[1], p2[1], p3[1], p4[1])
  629. ];
  630. };
  631. Util.inverseTransform = function Util_inverseTransform(m) {
  632. var d = m[0] * m[3] - m[1] * m[2];
  633. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  634. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  635. };
  636. // Apply a generic 3d matrix M on a 3-vector v:
  637. // | a b c | | X |
  638. // | d e f | x | Y |
  639. // | g h i | | Z |
  640. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  641. // with v as [X,Y,Z]
  642. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  643. return [
  644. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  645. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  646. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  647. ];
  648. };
  649. // This calculation uses Singular Value Decomposition.
  650. // The SVD can be represented with formula A = USV. We are interested in the
  651. // matrix S here because it represents the scale values.
  652. Util.singularValueDecompose2dScale =
  653. function Util_singularValueDecompose2dScale(m) {
  654. var transpose = [m[0], m[2], m[1], m[3]];
  655. // Multiply matrix m with its transpose.
  656. var a = m[0] * transpose[0] + m[1] * transpose[2];
  657. var b = m[0] * transpose[1] + m[1] * transpose[3];
  658. var c = m[2] * transpose[0] + m[3] * transpose[2];
  659. var d = m[2] * transpose[1] + m[3] * transpose[3];
  660. // Solve the second degree polynomial to get roots.
  661. var first = (a + d) / 2;
  662. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  663. var sx = first + second || 1;
  664. var sy = first - second || 1;
  665. // Scale values are the square roots of the eigenvalues.
  666. return [Math.sqrt(sx), Math.sqrt(sy)];
  667. };
  668. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  669. // For coordinate systems whose origin lies in the bottom-left, this
  670. // means normalization to (BL,TR) ordering. For systems with origin in the
  671. // top-left, this means (TL,BR) ordering.
  672. Util.normalizeRect = function Util_normalizeRect(rect) {
  673. var r = rect.slice(0); // clone rect
  674. if (rect[0] > rect[2]) {
  675. r[0] = rect[2];
  676. r[2] = rect[0];
  677. }
  678. if (rect[1] > rect[3]) {
  679. r[1] = rect[3];
  680. r[3] = rect[1];
  681. }
  682. return r;
  683. };
  684. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  685. // intersection of rect1 and rect2. If no intersection, returns 'false'
  686. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  687. Util.intersect = function Util_intersect(rect1, rect2) {
  688. function compare(a, b) {
  689. return a - b;
  690. }
  691. // Order points along the axes
  692. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  693. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  694. result = [];
  695. rect1 = Util.normalizeRect(rect1);
  696. rect2 = Util.normalizeRect(rect2);
  697. // X: first and second points belong to different rectangles?
  698. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  699. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  700. // Intersection must be between second and third points
  701. result[0] = orderedX[1];
  702. result[2] = orderedX[2];
  703. } else {
  704. return false;
  705. }
  706. // Y: first and second points belong to different rectangles?
  707. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  708. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  709. // Intersection must be between second and third points
  710. result[1] = orderedY[1];
  711. result[3] = orderedY[2];
  712. } else {
  713. return false;
  714. }
  715. return result;
  716. };
  717. Util.sign = function Util_sign(num) {
  718. return num < 0 ? -1 : 1;
  719. };
  720. var ROMAN_NUMBER_MAP = [
  721. '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  722. '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  723. '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
  724. ];
  725. /**
  726. * Converts positive integers to (upper case) Roman numerals.
  727. * @param {integer} number - The number that should be converted.
  728. * @param {boolean} lowerCase - Indicates if the result should be converted
  729. * to lower case letters. The default is false.
  730. * @return {string} The resulting Roman number.
  731. */
  732. Util.toRoman = function Util_toRoman(number, lowerCase) {
  733. assert(isInt(number) && number > 0,
  734. 'The number should be a positive integer.');
  735. var pos, romanBuf = [];
  736. // Thousands
  737. while (number >= 1000) {
  738. number -= 1000;
  739. romanBuf.push('M');
  740. }
  741. // Hundreds
  742. pos = (number / 100) | 0;
  743. number %= 100;
  744. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  745. // Tens
  746. pos = (number / 10) | 0;
  747. number %= 10;
  748. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  749. // Ones
  750. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  751. var romanStr = romanBuf.join('');
  752. return (lowerCase ? romanStr.toLowerCase() : romanStr);
  753. };
  754. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  755. Array.prototype.push.apply(arr1, arr2);
  756. };
  757. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  758. Array.prototype.unshift.apply(arr1, arr2);
  759. };
  760. Util.extendObj = function extendObj(obj1, obj2) {
  761. for (var key in obj2) {
  762. obj1[key] = obj2[key];
  763. }
  764. };
  765. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  766. name) {
  767. while (dict && !dict.has(name)) {
  768. dict = dict.get('Parent');
  769. }
  770. if (!dict) {
  771. return null;
  772. }
  773. return dict.get(name);
  774. };
  775. Util.inherit = function Util_inherit(sub, base, prototype) {
  776. sub.prototype = Object.create(base.prototype);
  777. sub.prototype.constructor = sub;
  778. for (var prop in prototype) {
  779. sub.prototype[prop] = prototype[prop];
  780. }
  781. };
  782. Util.loadScript = function Util_loadScript(src, callback) {
  783. var script = document.createElement('script');
  784. var loaded = false;
  785. script.setAttribute('src', src);
  786. if (callback) {
  787. script.onload = function() {
  788. if (!loaded) {
  789. callback();
  790. }
  791. loaded = true;
  792. };
  793. }
  794. document.getElementsByTagName('head')[0].appendChild(script);
  795. };
  796. return Util;
  797. })();
  798. /**
  799. * PDF page viewport created based on scale, rotation and offset.
  800. * @class
  801. * @alias PageViewport
  802. */
  803. var PageViewport = (function PageViewportClosure() {
  804. /**
  805. * @constructor
  806. * @private
  807. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  808. * @param scale {number} scale of the viewport.
  809. * @param rotation {number} rotations of the viewport in degrees.
  810. * @param offsetX {number} offset X
  811. * @param offsetY {number} offset Y
  812. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  813. */
  814. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  815. this.viewBox = viewBox;
  816. this.scale = scale;
  817. this.rotation = rotation;
  818. this.offsetX = offsetX;
  819. this.offsetY = offsetY;
  820. // creating transform to convert pdf coordinate system to the normal
  821. // canvas like coordinates taking in account scale and rotation
  822. var centerX = (viewBox[2] + viewBox[0]) / 2;
  823. var centerY = (viewBox[3] + viewBox[1]) / 2;
  824. var rotateA, rotateB, rotateC, rotateD;
  825. rotation = rotation % 360;
  826. rotation = rotation < 0 ? rotation + 360 : rotation;
  827. switch (rotation) {
  828. case 180:
  829. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  830. break;
  831. case 90:
  832. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  833. break;
  834. case 270:
  835. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  836. break;
  837. //case 0:
  838. default:
  839. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  840. break;
  841. }
  842. if (dontFlip) {
  843. rotateC = -rotateC; rotateD = -rotateD;
  844. }
  845. var offsetCanvasX, offsetCanvasY;
  846. var width, height;
  847. if (rotateA === 0) {
  848. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  849. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  850. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  851. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  852. } else {
  853. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  854. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  855. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  856. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  857. }
  858. // creating transform for the following operations:
  859. // translate(-centerX, -centerY), rotate and flip vertically,
  860. // scale, and translate(offsetCanvasX, offsetCanvasY)
  861. this.transform = [
  862. rotateA * scale,
  863. rotateB * scale,
  864. rotateC * scale,
  865. rotateD * scale,
  866. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  867. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  868. ];
  869. this.width = width;
  870. this.height = height;
  871. this.fontScale = scale;
  872. }
  873. PageViewport.prototype = /** @lends PageViewport.prototype */ {
  874. /**
  875. * Clones viewport with additional properties.
  876. * @param args {Object} (optional) If specified, may contain the 'scale' or
  877. * 'rotation' properties to override the corresponding properties in
  878. * the cloned viewport.
  879. * @returns {PageViewport} Cloned viewport.
  880. */
  881. clone: function PageViewPort_clone(args) {
  882. args = args || {};
  883. var scale = 'scale' in args ? args.scale : this.scale;
  884. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  885. return new PageViewport(this.viewBox.slice(), scale, rotation,
  886. this.offsetX, this.offsetY, args.dontFlip);
  887. },
  888. /**
  889. * Converts PDF point to the viewport coordinates. For examples, useful for
  890. * converting PDF location into canvas pixel coordinates.
  891. * @param x {number} X coordinate.
  892. * @param y {number} Y coordinate.
  893. * @returns {Object} Object that contains 'x' and 'y' properties of the
  894. * point in the viewport coordinate space.
  895. * @see {@link convertToPdfPoint}
  896. * @see {@link convertToViewportRectangle}
  897. */
  898. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  899. return Util.applyTransform([x, y], this.transform);
  900. },
  901. /**
  902. * Converts PDF rectangle to the viewport coordinates.
  903. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  904. * @returns {Array} Contains corresponding coordinates of the rectangle
  905. * in the viewport coordinate space.
  906. * @see {@link convertToViewportPoint}
  907. */
  908. convertToViewportRectangle:
  909. function PageViewport_convertToViewportRectangle(rect) {
  910. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  911. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  912. return [tl[0], tl[1], br[0], br[1]];
  913. },
  914. /**
  915. * Converts viewport coordinates to the PDF location. For examples, useful
  916. * for converting canvas pixel location into PDF one.
  917. * @param x {number} X coordinate.
  918. * @param y {number} Y coordinate.
  919. * @returns {Object} Object that contains 'x' and 'y' properties of the
  920. * point in the PDF coordinate space.
  921. * @see {@link convertToViewportPoint}
  922. */
  923. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  924. return Util.applyInverseTransform([x, y], this.transform);
  925. }
  926. };
  927. return PageViewport;
  928. })();
  929. var PDFStringTranslateTable = [
  930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  931. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  932. 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,
  933. 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,
  934. 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,
  935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  936. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  937. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  938. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  939. ];
  940. function stringToPDFString(str) {
  941. var i, n = str.length, strBuf = [];
  942. if (str[0] === '\xFE' && str[1] === '\xFF') {
  943. // UTF16BE BOM
  944. for (i = 2; i < n; i += 2) {
  945. strBuf.push(String.fromCharCode(
  946. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  947. }
  948. } else {
  949. for (i = 0; i < n; ++i) {
  950. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  951. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  952. }
  953. }
  954. return strBuf.join('');
  955. }
  956. function stringToUTF8String(str) {
  957. return decodeURIComponent(escape(str));
  958. }
  959. function utf8StringToString(str) {
  960. return unescape(encodeURIComponent(str));
  961. }
  962. function isEmptyObj(obj) {
  963. for (var key in obj) {
  964. return false;
  965. }
  966. return true;
  967. }
  968. function isBool(v) {
  969. return typeof v === 'boolean';
  970. }
  971. function isInt(v) {
  972. return typeof v === 'number' && ((v | 0) === v);
  973. }
  974. function isNum(v) {
  975. return typeof v === 'number';
  976. }
  977. function isString(v) {
  978. return typeof v === 'string';
  979. }
  980. function isArray(v) {
  981. return v instanceof Array;
  982. }
  983. function isArrayBuffer(v) {
  984. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  985. }
  986. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  987. function isSpace(ch) {
  988. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  989. }
  990. /**
  991. * Promise Capability object.
  992. *
  993. * @typedef {Object} PromiseCapability
  994. * @property {Promise} promise - A promise object.
  995. * @property {function} resolve - Fulfills the promise.
  996. * @property {function} reject - Rejects the promise.
  997. */
  998. /**
  999. * Creates a promise capability object.
  1000. * @alias createPromiseCapability
  1001. *
  1002. * @return {PromiseCapability} A capability object contains:
  1003. * - a Promise, resolve and reject methods.
  1004. */
  1005. function createPromiseCapability() {
  1006. var capability = {};
  1007. capability.promise = new Promise(function (resolve, reject) {
  1008. capability.resolve = resolve;
  1009. capability.reject = reject;
  1010. });
  1011. return capability;
  1012. }
  1013. /**
  1014. * Polyfill for Promises:
  1015. * The following promise implementation tries to generally implement the
  1016. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1017. * - There currently isn't a separate deferred and promise object.
  1018. * - Unhandled rejections eventually show an error if they aren't handled.
  1019. *
  1020. * Based off of the work in:
  1021. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1022. */
  1023. (function PromiseClosure() {
  1024. if (globalScope.Promise) {
  1025. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1026. if (typeof globalScope.Promise.all !== 'function') {
  1027. globalScope.Promise.all = function (iterable) {
  1028. var count = 0, results = [], resolve, reject;
  1029. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1030. resolve = resolve_;
  1031. reject = reject_;
  1032. });
  1033. iterable.forEach(function (p, i) {
  1034. count++;
  1035. p.then(function (result) {
  1036. results[i] = result;
  1037. count--;
  1038. if (count === 0) {
  1039. resolve(results);
  1040. }
  1041. }, reject);
  1042. });
  1043. if (count === 0) {
  1044. resolve(results);
  1045. }
  1046. return promise;
  1047. };
  1048. }
  1049. if (typeof globalScope.Promise.resolve !== 'function') {
  1050. globalScope.Promise.resolve = function (value) {
  1051. return new globalScope.Promise(function (resolve) { resolve(value); });
  1052. };
  1053. }
  1054. if (typeof globalScope.Promise.reject !== 'function') {
  1055. globalScope.Promise.reject = function (reason) {
  1056. return new globalScope.Promise(function (resolve, reject) {
  1057. reject(reason);
  1058. });
  1059. };
  1060. }
  1061. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1062. globalScope.Promise.prototype.catch = function (onReject) {
  1063. return globalScope.Promise.prototype.then(undefined, onReject);
  1064. };
  1065. }
  1066. return;
  1067. }
  1068. var STATUS_PENDING = 0;
  1069. var STATUS_RESOLVED = 1;
  1070. var STATUS_REJECTED = 2;
  1071. // In an attempt to avoid silent exceptions, unhandled rejections are
  1072. // tracked and if they aren't handled in a certain amount of time an
  1073. // error is logged.
  1074. var REJECTION_TIMEOUT = 500;
  1075. var HandlerManager = {
  1076. handlers: [],
  1077. running: false,
  1078. unhandledRejections: [],
  1079. pendingRejectionCheck: false,
  1080. scheduleHandlers: function scheduleHandlers(promise) {
  1081. if (promise._status === STATUS_PENDING) {
  1082. return;
  1083. }
  1084. this.handlers = this.handlers.concat(promise._handlers);
  1085. promise._handlers = [];
  1086. if (this.running) {
  1087. return;
  1088. }
  1089. this.running = true;
  1090. setTimeout(this.runHandlers.bind(this), 0);
  1091. },
  1092. runHandlers: function runHandlers() {
  1093. var RUN_TIMEOUT = 1; // ms
  1094. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1095. while (this.handlers.length > 0) {
  1096. var handler = this.handlers.shift();
  1097. var nextStatus = handler.thisPromise._status;
  1098. var nextValue = handler.thisPromise._value;
  1099. try {
  1100. if (nextStatus === STATUS_RESOLVED) {
  1101. if (typeof handler.onResolve === 'function') {
  1102. nextValue = handler.onResolve(nextValue);
  1103. }
  1104. } else if (typeof handler.onReject === 'function') {
  1105. nextValue = handler.onReject(nextValue);
  1106. nextStatus = STATUS_RESOLVED;
  1107. if (handler.thisPromise._unhandledRejection) {
  1108. this.removeUnhandeledRejection(handler.thisPromise);
  1109. }
  1110. }
  1111. } catch (ex) {
  1112. nextStatus = STATUS_REJECTED;
  1113. nextValue = ex;
  1114. }
  1115. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1116. if (Date.now() >= timeoutAt) {
  1117. break;
  1118. }
  1119. }
  1120. if (this.handlers.length > 0) {
  1121. setTimeout(this.runHandlers.bind(this), 0);
  1122. return;
  1123. }
  1124. this.running = false;
  1125. },
  1126. addUnhandledRejection: function addUnhandledRejection(promise) {
  1127. this.unhandledRejections.push({
  1128. promise: promise,
  1129. time: Date.now()
  1130. });
  1131. this.scheduleRejectionCheck();
  1132. },
  1133. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1134. promise._unhandledRejection = false;
  1135. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1136. if (this.unhandledRejections[i].promise === promise) {
  1137. this.unhandledRejections.splice(i);
  1138. i--;
  1139. }
  1140. }
  1141. },
  1142. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1143. if (this.pendingRejectionCheck) {
  1144. return;
  1145. }
  1146. this.pendingRejectionCheck = true;
  1147. setTimeout(function rejectionCheck() {
  1148. this.pendingRejectionCheck = false;
  1149. var now = Date.now();
  1150. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1151. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1152. var unhandled = this.unhandledRejections[i].promise._value;
  1153. var msg = 'Unhandled rejection: ' + unhandled;
  1154. if (unhandled.stack) {
  1155. msg += '\n' + unhandled.stack;
  1156. }
  1157. warn(msg);
  1158. this.unhandledRejections.splice(i);
  1159. i--;
  1160. }
  1161. }
  1162. if (this.unhandledRejections.length) {
  1163. this.scheduleRejectionCheck();
  1164. }
  1165. }.bind(this), REJECTION_TIMEOUT);
  1166. }
  1167. };
  1168. function Promise(resolver) {
  1169. this._status = STATUS_PENDING;
  1170. this._handlers = [];
  1171. try {
  1172. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1173. } catch (e) {
  1174. this._reject(e);
  1175. }
  1176. }
  1177. /**
  1178. * Builds a promise that is resolved when all the passed in promises are
  1179. * resolved.
  1180. * @param {array} promises array of data and/or promises to wait for.
  1181. * @return {Promise} New dependent promise.
  1182. */
  1183. Promise.all = function Promise_all(promises) {
  1184. var resolveAll, rejectAll;
  1185. var deferred = new Promise(function (resolve, reject) {
  1186. resolveAll = resolve;
  1187. rejectAll = reject;
  1188. });
  1189. var unresolved = promises.length;
  1190. var results = [];
  1191. if (unresolved === 0) {
  1192. resolveAll(results);
  1193. return deferred;
  1194. }
  1195. function reject(reason) {
  1196. if (deferred._status === STATUS_REJECTED) {
  1197. return;
  1198. }
  1199. results = [];
  1200. rejectAll(reason);
  1201. }
  1202. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1203. var promise = promises[i];
  1204. var resolve = (function(i) {
  1205. return function(value) {
  1206. if (deferred._status === STATUS_REJECTED) {
  1207. return;
  1208. }
  1209. results[i] = value;
  1210. unresolved--;
  1211. if (unresolved === 0) {
  1212. resolveAll(results);
  1213. }
  1214. };
  1215. })(i);
  1216. if (Promise.isPromise(promise)) {
  1217. promise.then(resolve, reject);
  1218. } else {
  1219. resolve(promise);
  1220. }
  1221. }
  1222. return deferred;
  1223. };
  1224. /**
  1225. * Checks if the value is likely a promise (has a 'then' function).
  1226. * @return {boolean} true if value is thenable
  1227. */
  1228. Promise.isPromise = function Promise_isPromise(value) {
  1229. return value && typeof value.then === 'function';
  1230. };
  1231. /**
  1232. * Creates resolved promise
  1233. * @param value resolve value
  1234. * @returns {Promise}
  1235. */
  1236. Promise.resolve = function Promise_resolve(value) {
  1237. return new Promise(function (resolve) { resolve(value); });
  1238. };
  1239. /**
  1240. * Creates rejected promise
  1241. * @param reason rejection value
  1242. * @returns {Promise}
  1243. */
  1244. Promise.reject = function Promise_reject(reason) {
  1245. return new Promise(function (resolve, reject) { reject(reason); });
  1246. };
  1247. Promise.prototype = {
  1248. _status: null,
  1249. _value: null,
  1250. _handlers: null,
  1251. _unhandledRejection: null,
  1252. _updateStatus: function Promise__updateStatus(status, value) {
  1253. if (this._status === STATUS_RESOLVED ||
  1254. this._status === STATUS_REJECTED) {
  1255. return;
  1256. }
  1257. if (status === STATUS_RESOLVED &&
  1258. Promise.isPromise(value)) {
  1259. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1260. this._updateStatus.bind(this, STATUS_REJECTED));
  1261. return;
  1262. }
  1263. this._status = status;
  1264. this._value = value;
  1265. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1266. this._unhandledRejection = true;
  1267. HandlerManager.addUnhandledRejection(this);
  1268. }
  1269. HandlerManager.scheduleHandlers(this);
  1270. },
  1271. _resolve: function Promise_resolve(value) {
  1272. this._updateStatus(STATUS_RESOLVED, value);
  1273. },
  1274. _reject: function Promise_reject(reason) {
  1275. this._updateStatus(STATUS_REJECTED, reason);
  1276. },
  1277. then: function Promise_then(onResolve, onReject) {
  1278. var nextPromise = new Promise(function (resolve, reject) {
  1279. this.resolve = resolve;
  1280. this.reject = reject;
  1281. });
  1282. this._handlers.push({
  1283. thisPromise: this,
  1284. onResolve: onResolve,
  1285. onReject: onReject,
  1286. nextPromise: nextPromise
  1287. });
  1288. HandlerManager.scheduleHandlers(this);
  1289. return nextPromise;
  1290. },
  1291. catch: function Promise_catch(onReject) {
  1292. return this.then(undefined, onReject);
  1293. }
  1294. };
  1295. globalScope.Promise = Promise;
  1296. })();
  1297. (function WeakMapClosure() {
  1298. if (globalScope.WeakMap) {
  1299. return;
  1300. }
  1301. var id = 0;
  1302. function WeakMap() {
  1303. this.id = '$weakmap' + (id++);
  1304. }
  1305. WeakMap.prototype = {
  1306. has: function(obj) {
  1307. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1308. },
  1309. get: function(obj, defaultValue) {
  1310. return this.has(obj) ? obj[this.id] : defaultValue;
  1311. },
  1312. set: function(obj, value) {
  1313. Object.defineProperty(obj, this.id, {
  1314. value: value,
  1315. enumerable: false,
  1316. configurable: true
  1317. });
  1318. },
  1319. delete: function(obj) {
  1320. delete obj[this.id];
  1321. }
  1322. };
  1323. globalScope.WeakMap = WeakMap;
  1324. })();
  1325. var StatTimer = (function StatTimerClosure() {
  1326. function rpad(str, pad, length) {
  1327. while (str.length < length) {
  1328. str += pad;
  1329. }
  1330. return str;
  1331. }
  1332. function StatTimer() {
  1333. this.started = Object.create(null);
  1334. this.times = [];
  1335. this.enabled = true;
  1336. }
  1337. StatTimer.prototype = {
  1338. time: function StatTimer_time(name) {
  1339. if (!this.enabled) {
  1340. return;
  1341. }
  1342. if (name in this.started) {
  1343. warn('Timer is already running for ' + name);
  1344. }
  1345. this.started[name] = Date.now();
  1346. },
  1347. timeEnd: function StatTimer_timeEnd(name) {
  1348. if (!this.enabled) {
  1349. return;
  1350. }
  1351. if (!(name in this.started)) {
  1352. warn('Timer has not been started for ' + name);
  1353. }
  1354. this.times.push({
  1355. 'name': name,
  1356. 'start': this.started[name],
  1357. 'end': Date.now()
  1358. });
  1359. // Remove timer from started so it can be called again.
  1360. delete this.started[name];
  1361. },
  1362. toString: function StatTimer_toString() {
  1363. var i, ii;
  1364. var times = this.times;
  1365. var out = '';
  1366. // Find the longest name for padding purposes.
  1367. var longest = 0;
  1368. for (i = 0, ii = times.length; i < ii; ++i) {
  1369. var name = times[i]['name'];
  1370. if (name.length > longest) {
  1371. longest = name.length;
  1372. }
  1373. }
  1374. for (i = 0, ii = times.length; i < ii; ++i) {
  1375. var span = times[i];
  1376. var duration = span.end - span.start;
  1377. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1378. }
  1379. return out;
  1380. }
  1381. };
  1382. return StatTimer;
  1383. })();
  1384. var createBlob = function createBlob(data, contentType) {
  1385. if (typeof Blob !== 'undefined') {
  1386. return new Blob([data], { type: contentType });
  1387. }
  1388. warn('The "Blob" constructor is not supported.');
  1389. };
  1390. var createObjectURL = (function createObjectURLClosure() {
  1391. // Blob/createObjectURL is not available, falling back to data schema.
  1392. var digits =
  1393. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1394. return function createObjectURL(data, contentType, forceDataSchema) {
  1395. if (!forceDataSchema &&
  1396. typeof URL !== 'undefined' && URL.createObjectURL) {
  1397. var blob = createBlob(data, contentType);
  1398. return URL.createObjectURL(blob);
  1399. }
  1400. var buffer = 'data:' + contentType + ';base64,';
  1401. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1402. var b1 = data[i] & 0xFF;
  1403. var b2 = data[i + 1] & 0xFF;
  1404. var b3 = data[i + 2] & 0xFF;
  1405. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1406. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1407. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1408. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1409. }
  1410. return buffer;
  1411. };
  1412. })();
  1413. function MessageHandler(sourceName, targetName, comObj) {
  1414. this.sourceName = sourceName;
  1415. this.targetName = targetName;
  1416. this.comObj = comObj;
  1417. this.callbackIndex = 1;
  1418. this.postMessageTransfers = true;
  1419. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1420. var ah = this.actionHandler = Object.create(null);
  1421. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1422. var data = event.data;
  1423. if (data.targetName !== this.sourceName) {
  1424. return;
  1425. }
  1426. if (data.isReply) {
  1427. var callbackId = data.callbackId;
  1428. if (data.callbackId in callbacksCapabilities) {
  1429. var callback = callbacksCapabilities[callbackId];
  1430. delete callbacksCapabilities[callbackId];
  1431. if ('error' in data) {
  1432. callback.reject(data.error);
  1433. } else {
  1434. callback.resolve(data.data);
  1435. }
  1436. } else {
  1437. error('Cannot resolve callback ' + callbackId);
  1438. }
  1439. } else if (data.action in ah) {
  1440. var action = ah[data.action];
  1441. if (data.callbackId) {
  1442. var sourceName = this.sourceName;
  1443. var targetName = data.sourceName;
  1444. Promise.resolve().then(function () {
  1445. return action[0].call(action[1], data.data);
  1446. }).then(function (result) {
  1447. comObj.postMessage({
  1448. sourceName: sourceName,
  1449. targetName: targetName,
  1450. isReply: true,
  1451. callbackId: data.callbackId,
  1452. data: result
  1453. });
  1454. }, function (reason) {
  1455. if (reason instanceof Error) {
  1456. // Serialize error to avoid "DataCloneError"
  1457. reason = reason + '';
  1458. }
  1459. comObj.postMessage({
  1460. sourceName: sourceName,
  1461. targetName: targetName,
  1462. isReply: true,
  1463. callbackId: data.callbackId,
  1464. error: reason
  1465. });
  1466. });
  1467. } else {
  1468. action[0].call(action[1], data.data);
  1469. }
  1470. } else {
  1471. error('Unknown action from worker: ' + data.action);
  1472. }
  1473. }.bind(this);
  1474. comObj.addEventListener('message', this._onComObjOnMessage);
  1475. }
  1476. MessageHandler.prototype = {
  1477. on: function messageHandlerOn(actionName, handler, scope) {
  1478. var ah = this.actionHandler;
  1479. if (ah[actionName]) {
  1480. error('There is already an actionName called "' + actionName + '"');
  1481. }
  1482. ah[actionName] = [handler, scope];
  1483. },
  1484. /**
  1485. * Sends a message to the comObj to invoke the action with the supplied data.
  1486. * @param {String} actionName Action to call.
  1487. * @param {JSON} data JSON data to send.
  1488. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1489. */
  1490. send: function messageHandlerSend(actionName, data, transfers) {
  1491. var message = {
  1492. sourceName: this.sourceName,
  1493. targetName: this.targetName,
  1494. action: actionName,
  1495. data: data
  1496. };
  1497. this.postMessage(message, transfers);
  1498. },
  1499. /**
  1500. * Sends a message to the comObj to invoke the action with the supplied data.
  1501. * Expects that other side will callback with the response.
  1502. * @param {String} actionName Action to call.
  1503. * @param {JSON} data JSON data to send.
  1504. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1505. * @returns {Promise} Promise to be resolved with response data.
  1506. */
  1507. sendWithPromise:
  1508. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1509. var callbackId = this.callbackIndex++;
  1510. var message = {
  1511. sourceName: this.sourceName,
  1512. targetName: this.targetName,
  1513. action: actionName,
  1514. data: data,
  1515. callbackId: callbackId
  1516. };
  1517. var capability = createPromiseCapability();
  1518. this.callbacksCapabilities[callbackId] = capability;
  1519. try {
  1520. this.postMessage(message, transfers);
  1521. } catch (e) {
  1522. capability.reject(e);
  1523. }
  1524. return capability.promise;
  1525. },
  1526. /**
  1527. * Sends raw message to the comObj.
  1528. * @private
  1529. * @param message {Object} Raw message.
  1530. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1531. */
  1532. postMessage: function (message, transfers) {
  1533. if (transfers && this.postMessageTransfers) {
  1534. this.comObj.postMessage(message, transfers);
  1535. } else {
  1536. this.comObj.postMessage(message);
  1537. }
  1538. },
  1539. destroy: function () {
  1540. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1541. }
  1542. };
  1543. function loadJpegStream(id, imageUrl, objs) {
  1544. var img = new Image();
  1545. img.onload = (function loadJpegStream_onloadClosure() {
  1546. objs.resolve(id, img);
  1547. });
  1548. img.onerror = (function loadJpegStream_onerrorClosure() {
  1549. objs.resolve(id, null);
  1550. warn('Error during JPEG image loading');
  1551. });
  1552. img.src = imageUrl;
  1553. }
  1554. // Polyfill from https://github.com/Polymer/URL
  1555. /* Any copyright is dedicated to the Public Domain.
  1556. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1557. (function checkURLConstructor(scope) {
  1558. /* jshint ignore:start */
  1559. // feature detect for URL constructor
  1560. var hasWorkingUrl = false;
  1561. try {
  1562. if (typeof URL === 'function' &&
  1563. typeof URL.prototype === 'object' &&
  1564. ('origin' in URL.prototype)) {
  1565. var u = new URL('b', 'http://a');
  1566. u.pathname = 'c%20d';
  1567. hasWorkingUrl = u.href === 'http://a/c%20d';
  1568. }
  1569. } catch(e) { }
  1570. if (hasWorkingUrl)
  1571. return;
  1572. var relative = Object.create(null);
  1573. relative['ftp'] = 21;
  1574. relative['file'] = 0;
  1575. relative['gopher'] = 70;
  1576. relative['http'] = 80;
  1577. relative['https'] = 443;
  1578. relative['ws'] = 80;
  1579. relative['wss'] = 443;
  1580. var relativePathDotMapping = Object.create(null);
  1581. relativePathDotMapping['%2e'] = '.';
  1582. relativePathDotMapping['.%2e'] = '..';
  1583. relativePathDotMapping['%2e.'] = '..';
  1584. relativePathDotMapping['%2e%2e'] = '..';
  1585. function isRelativeScheme(scheme) {
  1586. return relative[scheme] !== undefined;
  1587. }
  1588. function invalid() {
  1589. clear.call(this);
  1590. this._isInvalid = true;
  1591. }
  1592. function IDNAToASCII(h) {
  1593. if ('' == h) {
  1594. invalid.call(this)
  1595. }
  1596. // XXX
  1597. return h.toLowerCase()
  1598. }
  1599. function percentEscape(c) {
  1600. var unicode = c.charCodeAt(0);
  1601. if (unicode > 0x20 &&
  1602. unicode < 0x7F &&
  1603. // " # < > ? `
  1604. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1
  1605. ) {
  1606. return c;
  1607. }
  1608. return encodeURIComponent(c);
  1609. }
  1610. function percentEscapeQuery(c) {
  1611. // XXX This actually needs to encode c using encoding and then
  1612. // convert the bytes one-by-one.
  1613. var unicode = c.charCodeAt(0);
  1614. if (unicode > 0x20 &&
  1615. unicode < 0x7F &&
  1616. // " # < > ` (do not escape '?')
  1617. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1
  1618. ) {
  1619. return c;
  1620. }
  1621. return encodeURIComponent(c);
  1622. }
  1623. var EOF = undefined,
  1624. ALPHA = /[a-zA-Z]/,
  1625. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1626. function parse(input, stateOverride, base) {
  1627. function err(message) {
  1628. errors.push(message)
  1629. }
  1630. var state = stateOverride || 'scheme start',
  1631. cursor = 0,
  1632. buffer = '',
  1633. seenAt = false,
  1634. seenBracket = false,
  1635. errors = [];
  1636. loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
  1637. var c = input[cursor];
  1638. switch (state) {
  1639. case 'scheme start':
  1640. if (c && ALPHA.test(c)) {
  1641. buffer += c.toLowerCase(); // ASCII-safe
  1642. state = 'scheme';
  1643. } else if (!stateOverride) {
  1644. buffer = '';
  1645. state = 'no scheme';
  1646. continue;
  1647. } else {
  1648. err('Invalid scheme.');
  1649. break loop;
  1650. }
  1651. break;
  1652. case 'scheme':
  1653. if (c && ALPHANUMERIC.test(c)) {
  1654. buffer += c.toLowerCase(); // ASCII-safe
  1655. } else if (':' == c) {
  1656. this._scheme = buffer;
  1657. buffer = '';
  1658. if (stateOverride) {
  1659. break loop;
  1660. }
  1661. if (isRelativeScheme(this._scheme)) {
  1662. this._isRelative = true;
  1663. }
  1664. if ('file' == this._scheme) {
  1665. state = 'relative';
  1666. } else if (this._isRelative && base && base._scheme == this._scheme) {
  1667. state = 'relative or authority';
  1668. } else if (this._isRelative) {
  1669. state = 'authority first slash';
  1670. } else {
  1671. state = 'scheme data';
  1672. }
  1673. } else if (!stateOverride) {
  1674. buffer = '';
  1675. cursor = 0;
  1676. state = 'no scheme';
  1677. continue;
  1678. } else if (EOF == c) {
  1679. break loop;
  1680. } else {
  1681. err('Code point not allowed in scheme: ' + c)
  1682. break loop;
  1683. }
  1684. break;
  1685. case 'scheme data':
  1686. if ('?' == c) {
  1687. this._query = '?';
  1688. state = 'query';
  1689. } else if ('#' == c) {
  1690. this._fragment = '#';
  1691. state = 'fragment';
  1692. } else {
  1693. // XXX error handling
  1694. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1695. this._schemeData += percentEscape(c);
  1696. }
  1697. }
  1698. break;
  1699. case 'no scheme':
  1700. if (!base || !(isRelativeScheme(base._scheme))) {
  1701. err('Missing scheme.');
  1702. invalid.call(this);
  1703. } else {
  1704. state = 'relative';
  1705. continue;
  1706. }
  1707. break;
  1708. case 'relative or authority':
  1709. if ('/' == c && '/' == input[cursor+1]) {
  1710. state = 'authority ignore slashes';
  1711. } else {
  1712. err('Expected /, got: ' + c);
  1713. state = 'relative';
  1714. continue
  1715. }
  1716. break;
  1717. case 'relative':
  1718. this._isRelative = true;
  1719. if ('file' != this._scheme)
  1720. this._scheme = base._scheme;
  1721. if (EOF == c) {
  1722. this._host = base._host;
  1723. this._port = base._port;
  1724. this._path = base._path.slice();
  1725. this._query = base._query;
  1726. this._username = base._username;
  1727. this._password = base._password;
  1728. break loop;
  1729. } else if ('/' == c || '\\' == c) {
  1730. if ('\\' == c)
  1731. err('\\ is an invalid code point.');
  1732. state = 'relative slash';
  1733. } else if ('?' == c) {
  1734. this._host = base._host;
  1735. this._port = base._port;
  1736. this._path = base._path.slice();
  1737. this._query = '?';
  1738. this._username = base._username;
  1739. this._password = base._password;
  1740. state = 'query';
  1741. } else if ('#' == c) {
  1742. this._host = base._host;
  1743. this._port = base._port;
  1744. this._path = base._path.slice();
  1745. this._query = base._query;
  1746. this._fragment = '#';
  1747. this._username = base._username;
  1748. this._password = base._password;
  1749. state = 'fragment';
  1750. } else {
  1751. var nextC = input[cursor+1]
  1752. var nextNextC = input[cursor+2]
  1753. if (
  1754. 'file' != this._scheme || !ALPHA.test(c) ||
  1755. (nextC != ':' && nextC != '|') ||
  1756. (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) {
  1757. this._host = base._host;
  1758. this._port = base._port;
  1759. this._username = base._username;
  1760. this._password = base._password;
  1761. this._path = base._path.slice();
  1762. this._path.pop();
  1763. }
  1764. state = 'relative path';
  1765. continue;
  1766. }
  1767. break;
  1768. case 'relative slash':
  1769. if ('/' == c || '\\' == c) {
  1770. if ('\\' == c) {
  1771. err('\\ is an invalid code point.');
  1772. }
  1773. if ('file' == this._scheme) {
  1774. state = 'file host';
  1775. } else {
  1776. state = 'authority ignore slashes';
  1777. }
  1778. } else {
  1779. if ('file' != this._scheme) {
  1780. this._host = base._host;
  1781. this._port = base._port;
  1782. this._username = base._username;
  1783. this._password = base._password;
  1784. }
  1785. state = 'relative path';
  1786. continue;
  1787. }
  1788. break;
  1789. case 'authority first slash':
  1790. if ('/' == c) {
  1791. state = 'authority second slash';
  1792. } else {
  1793. err("Expected '/', got: " + c);
  1794. state = 'authority ignore slashes';
  1795. continue;
  1796. }
  1797. break;
  1798. case 'authority second slash':
  1799. state = 'authority ignore slashes';
  1800. if ('/' != c) {
  1801. err("Expected '/', got: " + c);
  1802. continue;
  1803. }
  1804. break;
  1805. case 'authority ignore slashes':
  1806. if ('/' != c && '\\' != c) {
  1807. state = 'authority';
  1808. continue;
  1809. } else {
  1810. err('Expected authority, got: ' + c);
  1811. }
  1812. break;
  1813. case 'authority':
  1814. if ('@' == c) {
  1815. if (seenAt) {
  1816. err('@ already seen.');
  1817. buffer += '%40';
  1818. }
  1819. seenAt = true;
  1820. for (var i = 0; i < buffer.length; i++) {
  1821. var cp = buffer[i];
  1822. if ('\t' == cp || '\n' == cp || '\r' == cp) {
  1823. err('Invalid whitespace in authority.');
  1824. continue;
  1825. }
  1826. // XXX check URL code points
  1827. if (':' == cp && null === this._password) {
  1828. this._password = '';
  1829. continue;
  1830. }
  1831. var tempC = percentEscape(cp);
  1832. (null !== this._password) ? this._password += tempC : this._username += tempC;
  1833. }
  1834. buffer = '';
  1835. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1836. cursor -= buffer.length;
  1837. buffer = '';
  1838. state = 'host';
  1839. continue;
  1840. } else {
  1841. buffer += c;
  1842. }
  1843. break;
  1844. case 'file host':
  1845. if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1846. if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
  1847. state = 'relative path';
  1848. } else if (buffer.length == 0) {
  1849. state = 'relative path start';
  1850. } else {
  1851. this._host = IDNAToASCII.call(this, buffer);
  1852. buffer = '';
  1853. state = 'relative path start';
  1854. }
  1855. continue;
  1856. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1857. err('Invalid whitespace in file host.');
  1858. } else {
  1859. buffer += c;
  1860. }
  1861. break;
  1862. case 'host':
  1863. case 'hostname':
  1864. if (':' == c && !seenBracket) {
  1865. // XXX host parsing
  1866. this._host = IDNAToASCII.call(this, buffer);
  1867. buffer = '';
  1868. state = 'port';
  1869. if ('hostname' == stateOverride) {
  1870. break loop;
  1871. }
  1872. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1873. this._host = IDNAToASCII.call(this, buffer);
  1874. buffer = '';
  1875. state = 'relative path start';
  1876. if (stateOverride) {
  1877. break loop;
  1878. }
  1879. continue;
  1880. } else if ('\t' != c && '\n' != c && '\r' != c) {
  1881. if ('[' == c) {
  1882. seenBracket = true;
  1883. } else if (']' == c) {
  1884. seenBracket = false;
  1885. }
  1886. buffer += c;
  1887. } else {
  1888. err('Invalid code point in host/hostname: ' + c);
  1889. }
  1890. break;
  1891. case 'port':
  1892. if (/[0-9]/.test(c)) {
  1893. buffer += c;
  1894. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
  1895. if ('' != buffer) {
  1896. var temp = parseInt(buffer, 10);
  1897. if (temp != relative[this._scheme]) {
  1898. this._port = temp + '';
  1899. }
  1900. buffer = '';
  1901. }
  1902. if (stateOverride) {
  1903. break loop;
  1904. }
  1905. state = 'relative path start';
  1906. continue;
  1907. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1908. err('Invalid code point in port: ' + c);
  1909. } else {
  1910. invalid.call(this);
  1911. }
  1912. break;
  1913. case 'relative path start':
  1914. if ('\\' == c)
  1915. err("'\\' not allowed in path.");
  1916. state = 'relative path';
  1917. if ('/' != c && '\\' != c) {
  1918. continue;
  1919. }
  1920. break;
  1921. case 'relative path':
  1922. if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) {
  1923. if ('\\' == c) {
  1924. err('\\ not allowed in relative path.');
  1925. }
  1926. var tmp;
  1927. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1928. buffer = tmp;
  1929. }
  1930. if ('..' == buffer) {
  1931. this._path.pop();
  1932. if ('/' != c && '\\' != c) {
  1933. this._path.push('');
  1934. }
  1935. } else if ('.' == buffer && '/' != c && '\\' != c) {
  1936. this._path.push('');
  1937. } else if ('.' != buffer) {
  1938. if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
  1939. buffer = buffer[0] + ':';
  1940. }
  1941. this._path.push(buffer);
  1942. }
  1943. buffer = '';
  1944. if ('?' == c) {
  1945. this._query = '?';
  1946. state = 'query';
  1947. } else if ('#' == c) {
  1948. this._fragment = '#';
  1949. state = 'fragment';
  1950. }
  1951. } else if ('\t' != c && '\n' != c && '\r' != c) {
  1952. buffer += percentEscape(c);
  1953. }
  1954. break;
  1955. case 'query':
  1956. if (!stateOverride && '#' == c) {
  1957. this._fragment = '#';
  1958. state = 'fragment';
  1959. } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1960. this._query += percentEscapeQuery(c);
  1961. }
  1962. break;
  1963. case 'fragment':
  1964. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1965. this._fragment += c;
  1966. }
  1967. break;
  1968. }
  1969. cursor++;
  1970. }
  1971. }
  1972. function clear() {
  1973. this._scheme = '';
  1974. this._schemeData = '';
  1975. this._username = '';
  1976. this._password = null;
  1977. this._host = '';
  1978. this._port = '';
  1979. this._path = [];
  1980. this._query = '';
  1981. this._fragment = '';
  1982. this._isInvalid = false;
  1983. this._isRelative = false;
  1984. }
  1985. // Does not process domain names or IP addresses.
  1986. // Does not handle encoding for the query parameter.
  1987. function jURL(url, base /* , encoding */) {
  1988. if (base !== undefined && !(base instanceof jURL))
  1989. base = new jURL(String(base));
  1990. this._url = url;
  1991. clear.call(this);
  1992. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  1993. // encoding = encoding || 'utf-8'
  1994. parse.call(this, input, null, base);
  1995. }
  1996. jURL.prototype = {
  1997. toString: function() {
  1998. return this.href;
  1999. },
  2000. get href() {
  2001. if (this._isInvalid)
  2002. return this._url;
  2003. var authority = '';
  2004. if ('' != this._username || null != this._password) {
  2005. authority = this._username +
  2006. (null != this._password ? ':' + this._password : '') + '@';
  2007. }
  2008. return this.protocol +
  2009. (this._isRelative ? '//' + authority + this.host : '') +
  2010. this.pathname + this._query + this._fragment;
  2011. },
  2012. set href(href) {
  2013. clear.call(this);
  2014. parse.call(this, href);
  2015. },
  2016. get protocol() {
  2017. return this._scheme + ':';
  2018. },
  2019. set protocol(protocol) {
  2020. if (this._isInvalid)
  2021. return;
  2022. parse.call(this, protocol + ':', 'scheme start');
  2023. },
  2024. get host() {
  2025. return this._isInvalid ? '' : this._port ?
  2026. this._host + ':' + this._port : this._host;
  2027. },
  2028. set host(host) {
  2029. if (this._isInvalid || !this._isRelative)
  2030. return;
  2031. parse.call(this, host, 'host');
  2032. },
  2033. get hostname() {
  2034. return this._host;
  2035. },
  2036. set hostname(hostname) {
  2037. if (this._isInvalid || !this._isRelative)
  2038. return;
  2039. parse.call(this, hostname, 'hostname');
  2040. },
  2041. get port() {
  2042. return this._port;
  2043. },
  2044. set port(port) {
  2045. if (this._isInvalid || !this._isRelative)
  2046. return;
  2047. parse.call(this, port, 'port');
  2048. },
  2049. get pathname() {
  2050. return this._isInvalid ? '' : this._isRelative ?
  2051. '/' + this._path.join('/') : this._schemeData;
  2052. },
  2053. set pathname(pathname) {
  2054. if (this._isInvalid || !this._isRelative)
  2055. return;
  2056. this._path = [];
  2057. parse.call(this, pathname, 'relative path start');
  2058. },
  2059. get search() {
  2060. return this._isInvalid || !this._query || '?' == this._query ?
  2061. '' : this._query;
  2062. },
  2063. set search(search) {
  2064. if (this._isInvalid || !this._isRelative)
  2065. return;
  2066. this._query = '?';
  2067. if ('?' == search[0])
  2068. search = search.slice(1);
  2069. parse.call(this, search, 'query');
  2070. },
  2071. get hash() {
  2072. return this._isInvalid || !this._fragment || '#' == this._fragment ?
  2073. '' : this._fragment;
  2074. },
  2075. set hash(hash) {
  2076. if (this._isInvalid)
  2077. return;
  2078. this._fragment = '#';
  2079. if ('#' == hash[0])
  2080. hash = hash.slice(1);
  2081. parse.call(this, hash, 'fragment');
  2082. },
  2083. get origin() {
  2084. var host;
  2085. if (this._isInvalid || !this._scheme) {
  2086. return '';
  2087. }
  2088. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2089. // Gecko throws error for "data://"
  2090. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2091. // Gecko returns String("") for file: mailto:
  2092. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2093. switch (this._scheme) {
  2094. case 'data':
  2095. case 'file':
  2096. case 'javascript':
  2097. case 'mailto':
  2098. return 'null';
  2099. }
  2100. host = this.host;
  2101. if (!host) {
  2102. return '';
  2103. }
  2104. return this._scheme + '://' + host;
  2105. }
  2106. };
  2107. // Copy over the static methods
  2108. var OriginalURL = scope.URL;
  2109. if (OriginalURL) {
  2110. jURL.createObjectURL = function(blob) {
  2111. // IE extension allows a second optional options argument.
  2112. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2113. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2114. };
  2115. jURL.revokeObjectURL = function(url) {
  2116. OriginalURL.revokeObjectURL(url);
  2117. };
  2118. }
  2119. scope.URL = jURL;
  2120. /* jshint ignore:end */
  2121. })(globalScope);
  2122. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2123. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2124. exports.OPS = OPS;
  2125. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2126. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2127. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2128. exports.AnnotationFlag = AnnotationFlag;
  2129. exports.AnnotationType = AnnotationType;
  2130. exports.FontType = FontType;
  2131. exports.ImageKind = ImageKind;
  2132. exports.InvalidPDFException = InvalidPDFException;
  2133. exports.MessageHandler = MessageHandler;
  2134. exports.MissingDataException = MissingDataException;
  2135. exports.MissingPDFException = MissingPDFException;
  2136. exports.NotImplementedException = NotImplementedException;
  2137. exports.PageViewport = PageViewport;
  2138. exports.PasswordException = PasswordException;
  2139. exports.PasswordResponses = PasswordResponses;
  2140. exports.StatTimer = StatTimer;
  2141. exports.StreamType = StreamType;
  2142. exports.TextRenderingMode = TextRenderingMode;
  2143. exports.UnexpectedResponseException = UnexpectedResponseException;
  2144. exports.UnknownErrorException = UnknownErrorException;
  2145. exports.Util = Util;
  2146. exports.XRefParseException = XRefParseException;
  2147. exports.arrayByteLength = arrayByteLength;
  2148. exports.arraysToBytes = arraysToBytes;
  2149. exports.assert = assert;
  2150. exports.bytesToString = bytesToString;
  2151. exports.createBlob = createBlob;
  2152. exports.createPromiseCapability = createPromiseCapability;
  2153. exports.createObjectURL = createObjectURL;
  2154. exports.deprecated = deprecated;
  2155. exports.error = error;
  2156. exports.getLookupTableFactory = getLookupTableFactory;
  2157. exports.getVerbosityLevel = getVerbosityLevel;
  2158. exports.globalScope = globalScope;
  2159. exports.info = info;
  2160. exports.isArray = isArray;
  2161. exports.isArrayBuffer = isArrayBuffer;
  2162. exports.isBool = isBool;
  2163. exports.isEmptyObj = isEmptyObj;
  2164. exports.isInt = isInt;
  2165. exports.isNum = isNum;
  2166. exports.isString = isString;
  2167. exports.isSpace = isSpace;
  2168. exports.isSameOrigin = isSameOrigin;
  2169. exports.isValidUrl = isValidUrl;
  2170. exports.isLittleEndian = isLittleEndian;
  2171. exports.isEvalSupported = isEvalSupported;
  2172. exports.loadJpegStream = loadJpegStream;
  2173. exports.log2 = log2;
  2174. exports.readInt8 = readInt8;
  2175. exports.readUint16 = readUint16;
  2176. exports.readUint32 = readUint32;
  2177. exports.removeNullCharacters = removeNullCharacters;
  2178. exports.setVerbosityLevel = setVerbosityLevel;
  2179. exports.shadow = shadow;
  2180. exports.string32 = string32;
  2181. exports.stringToBytes = stringToBytes;
  2182. exports.stringToPDFString = stringToPDFString;
  2183. exports.stringToUTF8String = stringToUTF8String;
  2184. exports.utf8StringToString = utf8StringToString;
  2185. exports.warn = warn;
  2186. }));
  2187. (function (root, factory) {
  2188. {
  2189. factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil);
  2190. }
  2191. }(this, function (exports, sharedUtil) {
  2192. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2193. var warn = sharedUtil.warn;
  2194. /**
  2195. * Optimised CSS custom property getter/setter.
  2196. * @class
  2197. */
  2198. var CustomStyle = (function CustomStyleClosure() {
  2199. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2200. // animate-css-transforms-firefox-webkit.html
  2201. // in some versions of IE9 it is critical that ms appear in this list
  2202. // before Moz
  2203. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  2204. var _cache = Object.create(null);
  2205. function CustomStyle() {}
  2206. CustomStyle.getProp = function get(propName, element) {
  2207. // check cache only when no element is given
  2208. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2209. return _cache[propName];
  2210. }
  2211. element = element || document.documentElement;
  2212. var style = element.style, prefixed, uPropName;
  2213. // test standard property first
  2214. if (typeof style[propName] === 'string') {
  2215. return (_cache[propName] = propName);
  2216. }
  2217. // capitalize
  2218. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2219. // test vendor specific properties
  2220. for (var i = 0, l = prefixes.length; i < l; i++) {
  2221. prefixed = prefixes[i] + uPropName;
  2222. if (typeof style[prefixed] === 'string') {
  2223. return (_cache[propName] = prefixed);
  2224. }
  2225. }
  2226. //if all fails then set to undefined
  2227. return (_cache[propName] = 'undefined');
  2228. };
  2229. CustomStyle.setProp = function set(propName, element, str) {
  2230. var prop = this.getProp(propName);
  2231. if (prop !== 'undefined') {
  2232. element.style[prop] = str;
  2233. }
  2234. };
  2235. return CustomStyle;
  2236. })();
  2237. function hasCanvasTypedArrays() {
  2238. var canvas = document.createElement('canvas');
  2239. canvas.width = canvas.height = 1;
  2240. var ctx = canvas.getContext('2d');
  2241. var imageData = ctx.createImageData(1, 1);
  2242. return (typeof imageData.data.buffer !== 'undefined');
  2243. }
  2244. var LinkTarget = {
  2245. NONE: 0, // Default value.
  2246. SELF: 1,
  2247. BLANK: 2,
  2248. PARENT: 3,
  2249. TOP: 4,
  2250. };
  2251. var LinkTargetStringMap = [
  2252. '',
  2253. '_self',
  2254. '_blank',
  2255. '_parent',
  2256. '_top'
  2257. ];
  2258. /**
  2259. * @typedef ExternalLinkParameters
  2260. * @typedef {Object} ExternalLinkParameters
  2261. * @property {string} url - An absolute URL.
  2262. * @property {LinkTarget} target - The link target.
  2263. * @property {string} rel - The link relationship.
  2264. */
  2265. /**
  2266. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2267. * @param {HTMLLinkElement} link - The link element.
  2268. * @param {ExternalLinkParameters} params
  2269. */
  2270. function addLinkAttributes(link, params) {
  2271. var url = params && params.url;
  2272. link.href = link.title = (url ? removeNullCharacters(url) : '');
  2273. if (url) {
  2274. var target = params.target;
  2275. if (typeof target === 'undefined') {
  2276. target = getDefaultSetting('externalLinkTarget');
  2277. }
  2278. link.target = LinkTargetStringMap[target];
  2279. var rel = params.rel;
  2280. if (typeof rel === 'undefined') {
  2281. rel = getDefaultSetting('externalLinkRel');
  2282. }
  2283. link.rel = rel;
  2284. }
  2285. }
  2286. // Gets the file name from a given URL.
  2287. function getFilenameFromUrl(url) {
  2288. var anchor = url.indexOf('#');
  2289. var query = url.indexOf('?');
  2290. var end = Math.min(
  2291. anchor > 0 ? anchor : url.length,
  2292. query > 0 ? query : url.length);
  2293. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2294. }
  2295. function getDefaultSetting(id) {
  2296. // The list of the settings and their default is maintained for backward
  2297. // compatibility and shall not be extended or modified. See also global.js.
  2298. var globalSettings = sharedUtil.globalScope.PDFJS;
  2299. switch (id) {
  2300. case 'pdfBug':
  2301. return globalSettings ? globalSettings.pdfBug : false;
  2302. case 'disableAutoFetch':
  2303. return globalSettings ? globalSettings.disableAutoFetch : false;
  2304. case 'disableStream':
  2305. return globalSettings ? globalSettings.disableStream : false;
  2306. case 'disableRange':
  2307. return globalSettings ? globalSettings.disableRange : false;
  2308. case 'disableFontFace':
  2309. return globalSettings ? globalSettings.disableFontFace : false;
  2310. case 'disableCreateObjectURL':
  2311. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2312. case 'disableWebGL':
  2313. return globalSettings ? globalSettings.disableWebGL : true;
  2314. case 'cMapUrl':
  2315. return globalSettings ? globalSettings.cMapUrl : null;
  2316. case 'cMapPacked':
  2317. return globalSettings ? globalSettings.cMapPacked : false;
  2318. case 'postMessageTransfers':
  2319. return globalSettings ? globalSettings.postMessageTransfers : true;
  2320. case 'workerSrc':
  2321. return globalSettings ? globalSettings.workerSrc : null;
  2322. case 'disableWorker':
  2323. return globalSettings ? globalSettings.disableWorker : false;
  2324. case 'maxImageSize':
  2325. return globalSettings ? globalSettings.maxImageSize : -1;
  2326. case 'imageResourcesPath':
  2327. return globalSettings ? globalSettings.imageResourcesPath : '';
  2328. case 'isEvalSupported':
  2329. return globalSettings ? globalSettings.isEvalSupported : true;
  2330. case 'externalLinkTarget':
  2331. if (!globalSettings) {
  2332. return LinkTarget.NONE;
  2333. }
  2334. switch (globalSettings.externalLinkTarget) {
  2335. case LinkTarget.NONE:
  2336. case LinkTarget.SELF:
  2337. case LinkTarget.BLANK:
  2338. case LinkTarget.PARENT:
  2339. case LinkTarget.TOP:
  2340. return globalSettings.externalLinkTarget;
  2341. }
  2342. warn('PDFJS.externalLinkTarget is invalid: ' +
  2343. globalSettings.externalLinkTarget);
  2344. // Reset the external link target, to suppress further warnings.
  2345. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2346. return LinkTarget.NONE;
  2347. case 'externalLinkRel':
  2348. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2349. case 'enableStats':
  2350. return !!(globalSettings && globalSettings.enableStats);
  2351. default:
  2352. throw new Error('Unknown default setting: ' + id);
  2353. }
  2354. }
  2355. function isExternalLinkTargetSet() {
  2356. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2357. switch (externalLinkTarget) {
  2358. case LinkTarget.NONE:
  2359. return false;
  2360. case LinkTarget.SELF:
  2361. case LinkTarget.BLANK:
  2362. case LinkTarget.PARENT:
  2363. case LinkTarget.TOP:
  2364. return true;
  2365. }
  2366. }
  2367. exports.CustomStyle = CustomStyle;
  2368. exports.addLinkAttributes = addLinkAttributes;
  2369. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2370. exports.getFilenameFromUrl = getFilenameFromUrl;
  2371. exports.LinkTarget = LinkTarget;
  2372. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2373. exports.getDefaultSetting = getDefaultSetting;
  2374. }));
  2375. (function (root, factory) {
  2376. {
  2377. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil);
  2378. }
  2379. }(this, function (exports, sharedUtil) {
  2380. var assert = sharedUtil.assert;
  2381. var bytesToString = sharedUtil.bytesToString;
  2382. var string32 = sharedUtil.string32;
  2383. var shadow = sharedUtil.shadow;
  2384. var warn = sharedUtil.warn;
  2385. function FontLoader(docId) {
  2386. this.docId = docId;
  2387. this.styleElement = null;
  2388. this.nativeFontFaces = [];
  2389. this.loadTestFontId = 0;
  2390. this.loadingContext = {
  2391. requests: [],
  2392. nextRequestId: 0
  2393. };
  2394. }
  2395. FontLoader.prototype = {
  2396. insertRule: function fontLoaderInsertRule(rule) {
  2397. var styleElement = this.styleElement;
  2398. if (!styleElement) {
  2399. styleElement = this.styleElement = document.createElement('style');
  2400. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2401. document.documentElement.getElementsByTagName('head')[0].appendChild(
  2402. styleElement);
  2403. }
  2404. var styleSheet = styleElement.sheet;
  2405. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2406. },
  2407. clear: function fontLoaderClear() {
  2408. var styleElement = this.styleElement;
  2409. if (styleElement) {
  2410. styleElement.parentNode.removeChild(styleElement);
  2411. styleElement = this.styleElement = null;
  2412. }
  2413. this.nativeFontFaces.forEach(function(nativeFontFace) {
  2414. document.fonts.delete(nativeFontFace);
  2415. });
  2416. this.nativeFontFaces.length = 0;
  2417. },
  2418. get loadTestFont() {
  2419. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2420. // height.
  2421. return shadow(this, 'loadTestFont', atob(
  2422. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  2423. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  2424. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  2425. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  2426. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  2427. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  2428. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  2429. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  2430. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  2431. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  2432. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  2433. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  2434. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  2435. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2436. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2437. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2438. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  2439. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  2440. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  2441. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  2442. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  2443. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  2444. ));
  2445. },
  2446. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  2447. this.nativeFontFaces.push(nativeFontFace);
  2448. document.fonts.add(nativeFontFace);
  2449. },
  2450. bind: function fontLoaderBind(fonts, callback) {
  2451. var rules = [];
  2452. var fontsToLoad = [];
  2453. var fontLoadPromises = [];
  2454. var getNativeFontPromise = function(nativeFontFace) {
  2455. // Return a promise that is always fulfilled, even when the font fails to
  2456. // load.
  2457. return nativeFontFace.loaded.catch(function(e) {
  2458. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2459. });
  2460. };
  2461. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2462. var font = fonts[i];
  2463. // Add the font to the DOM only once or skip if the font
  2464. // is already loaded.
  2465. if (font.attached || font.loading === false) {
  2466. continue;
  2467. }
  2468. font.attached = true;
  2469. if (FontLoader.isFontLoadingAPISupported) {
  2470. var nativeFontFace = font.createNativeFontFace();
  2471. if (nativeFontFace) {
  2472. this.addNativeFontFace(nativeFontFace);
  2473. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2474. }
  2475. } else {
  2476. var rule = font.createFontFaceRule();
  2477. if (rule) {
  2478. this.insertRule(rule);
  2479. rules.push(rule);
  2480. fontsToLoad.push(font);
  2481. }
  2482. }
  2483. }
  2484. var request = this.queueLoadingCallback(callback);
  2485. if (FontLoader.isFontLoadingAPISupported) {
  2486. Promise.all(fontLoadPromises).then(function() {
  2487. request.complete();
  2488. });
  2489. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2490. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2491. } else {
  2492. request.complete();
  2493. }
  2494. },
  2495. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  2496. function LoadLoader_completeRequest() {
  2497. assert(!request.end, 'completeRequest() cannot be called twice');
  2498. request.end = Date.now();
  2499. // sending all completed requests in order how they were queued
  2500. while (context.requests.length > 0 && context.requests[0].end) {
  2501. var otherRequest = context.requests.shift();
  2502. setTimeout(otherRequest.callback, 0);
  2503. }
  2504. }
  2505. var context = this.loadingContext;
  2506. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  2507. var request = {
  2508. id: requestId,
  2509. complete: LoadLoader_completeRequest,
  2510. callback: callback,
  2511. started: Date.now()
  2512. };
  2513. context.requests.push(request);
  2514. return request;
  2515. },
  2516. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  2517. fonts,
  2518. request) {
  2519. /** Hack begin */
  2520. // There's currently no event when a font has finished downloading so the
  2521. // following code is a dirty hack to 'guess' when a font is
  2522. // ready. It's assumed fonts are loaded in order, so add a known test
  2523. // font after the desired fonts and then test for the loading of that
  2524. // test font.
  2525. function int32(data, offset) {
  2526. return (data.charCodeAt(offset) << 24) |
  2527. (data.charCodeAt(offset + 1) << 16) |
  2528. (data.charCodeAt(offset + 2) << 8) |
  2529. (data.charCodeAt(offset + 3) & 0xff);
  2530. }
  2531. function spliceString(s, offset, remove, insert) {
  2532. var chunk1 = s.substr(0, offset);
  2533. var chunk2 = s.substr(offset + remove);
  2534. return chunk1 + insert + chunk2;
  2535. }
  2536. var i, ii;
  2537. var canvas = document.createElement('canvas');
  2538. canvas.width = 1;
  2539. canvas.height = 1;
  2540. var ctx = canvas.getContext('2d');
  2541. var called = 0;
  2542. function isFontReady(name, callback) {
  2543. called++;
  2544. // With setTimeout clamping this gives the font ~100ms to load.
  2545. if(called > 30) {
  2546. warn('Load test font never loaded.');
  2547. callback();
  2548. return;
  2549. }
  2550. ctx.font = '30px ' + name;
  2551. ctx.fillText('.', 0, 20);
  2552. var imageData = ctx.getImageData(0, 0, 1, 1);
  2553. if (imageData.data[3] > 0) {
  2554. callback();
  2555. return;
  2556. }
  2557. setTimeout(isFontReady.bind(null, name, callback));
  2558. }
  2559. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2560. // Chromium seems to cache fonts based on a hash of the actual font data,
  2561. // so the font must be modified for each load test else it will appear to
  2562. // be loaded already.
  2563. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2564. // font by splitting it in chunks before hand and padding the font id.
  2565. var data = this.loadTestFont;
  2566. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  2567. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  2568. loadTestFontId);
  2569. // CFF checksum is important for IE, adjusting it
  2570. var CFF_CHECKSUM_OFFSET = 16;
  2571. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  2572. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2573. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2574. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  2575. }
  2576. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  2577. checksum = (checksum - XXXX_VALUE +
  2578. int32(loadTestFontId + 'XXX', i)) | 0;
  2579. }
  2580. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2581. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2582. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  2583. url + '}';
  2584. this.insertRule(rule);
  2585. var names = [];
  2586. for (i = 0, ii = fonts.length; i < ii; i++) {
  2587. names.push(fonts[i].loadedName);
  2588. }
  2589. names.push(loadTestFontId);
  2590. var div = document.createElement('div');
  2591. div.setAttribute('style',
  2592. 'visibility: hidden;' +
  2593. 'width: 10px; height: 10px;' +
  2594. 'position: absolute; top: 0px; left: 0px;');
  2595. for (i = 0, ii = names.length; i < ii; ++i) {
  2596. var span = document.createElement('span');
  2597. span.textContent = 'Hi';
  2598. span.style.fontFamily = names[i];
  2599. div.appendChild(span);
  2600. }
  2601. document.body.appendChild(div);
  2602. isFontReady(loadTestFontId, function() {
  2603. document.body.removeChild(div);
  2604. request.complete();
  2605. });
  2606. /** Hack end */
  2607. }
  2608. };
  2609. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' &&
  2610. !!document.fonts;
  2611. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2612. get: function () {
  2613. if (typeof navigator === 'undefined') {
  2614. // node.js - we can pretend sync font loading is supported.
  2615. return shadow(FontLoader, 'isSyncFontLoadingSupported', true);
  2616. }
  2617. var supported = false;
  2618. // User agent string sniffing is bad, but there is no reliable way to tell
  2619. // if font is fully loaded and ready to be used with canvas.
  2620. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2621. if (m && m[1] >= 14) {
  2622. supported = true;
  2623. }
  2624. // TODO other browsers
  2625. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  2626. },
  2627. enumerable: true,
  2628. configurable: true
  2629. });
  2630. var IsEvalSupportedCached = {
  2631. get value() {
  2632. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2633. }
  2634. };
  2635. var FontFaceObject = (function FontFaceObjectClosure() {
  2636. function FontFaceObject(translatedData, options) {
  2637. this.compiledGlyphs = Object.create(null);
  2638. // importing translated data
  2639. for (var i in translatedData) {
  2640. this[i] = translatedData[i];
  2641. }
  2642. this.options = options;
  2643. }
  2644. FontFaceObject.prototype = {
  2645. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2646. if (!this.data) {
  2647. return null;
  2648. }
  2649. if (this.options.disableFontFace) {
  2650. this.disableFontFace = true;
  2651. return null;
  2652. }
  2653. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2654. if (this.options.fontRegistry) {
  2655. this.options.fontRegistry.registerFont(this);
  2656. }
  2657. return nativeFontFace;
  2658. },
  2659. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2660. if (!this.data) {
  2661. return null;
  2662. }
  2663. if (this.options.disableFontFace) {
  2664. this.disableFontFace = true;
  2665. return null;
  2666. }
  2667. var data = bytesToString(new Uint8Array(this.data));
  2668. var fontName = this.loadedName;
  2669. // Add the font-face rule to the document
  2670. var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');');
  2671. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2672. if (this.options.fontRegistry) {
  2673. this.options.fontRegistry.registerFont(this, url);
  2674. }
  2675. return rule;
  2676. },
  2677. getPathGenerator:
  2678. function FontFaceObject_getPathGenerator(objs, character) {
  2679. if (!(character in this.compiledGlyphs)) {
  2680. var cmds = objs.get(this.loadedName + '_path_' + character);
  2681. var current, i, len;
  2682. // If we can, compile cmds into JS for MAXIMUM SPEED
  2683. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2684. var args, js = '';
  2685. for (i = 0, len = cmds.length; i < len; i++) {
  2686. current = cmds[i];
  2687. if (current.args !== undefined) {
  2688. args = current.args.join(',');
  2689. } else {
  2690. args = '';
  2691. }
  2692. js += 'c.' + current.cmd + '(' + args + ');\n';
  2693. }
  2694. /* jshint -W054 */
  2695. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2696. } else {
  2697. // But fall back on using Function.prototype.apply() if we're
  2698. // blocked from using eval() for whatever reason (like CSP policies)
  2699. this.compiledGlyphs[character] = function(c, size) {
  2700. for (i = 0, len = cmds.length; i < len; i++) {
  2701. current = cmds[i];
  2702. if (current.cmd === 'scale') {
  2703. current.args = [size, -size];
  2704. }
  2705. c[current.cmd].apply(c, current.args);
  2706. }
  2707. };
  2708. }
  2709. }
  2710. return this.compiledGlyphs[character];
  2711. }
  2712. };
  2713. return FontFaceObject;
  2714. })();
  2715. exports.FontFaceObject = FontFaceObject;
  2716. exports.FontLoader = FontLoader;
  2717. }));
  2718. (function (root, factory) {
  2719. {
  2720. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  2721. }
  2722. }(this, function (exports, sharedUtil) {
  2723. var error = sharedUtil.error;
  2724. function fixMetadata(meta) {
  2725. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2726. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2727. function(code, d1, d2, d3) {
  2728. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2729. });
  2730. var chars = '';
  2731. for (var i = 0; i < bytes.length; i += 2) {
  2732. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2733. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2734. code !== 38 && false ? String.fromCharCode(code) :
  2735. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2736. }
  2737. return '>' + chars;
  2738. });
  2739. }
  2740. function Metadata(meta) {
  2741. if (typeof meta === 'string') {
  2742. // Ghostscript produces invalid metadata
  2743. meta = fixMetadata(meta);
  2744. var parser = new DOMParser();
  2745. meta = parser.parseFromString(meta, 'application/xml');
  2746. } else if (!(meta instanceof Document)) {
  2747. error('Metadata: Invalid metadata object');
  2748. }
  2749. this.metaDocument = meta;
  2750. this.metadata = Object.create(null);
  2751. this.parse();
  2752. }
  2753. Metadata.prototype = {
  2754. parse: function Metadata_parse() {
  2755. var doc = this.metaDocument;
  2756. var rdf = doc.documentElement;
  2757. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2758. rdf = rdf.firstChild;
  2759. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2760. rdf = rdf.nextSibling;
  2761. }
  2762. }
  2763. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2764. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2765. return;
  2766. }
  2767. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2768. for (i = 0, length = children.length; i < length; i++) {
  2769. desc = children[i];
  2770. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2771. continue;
  2772. }
  2773. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2774. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2775. entry = desc.childNodes[ii];
  2776. name = entry.nodeName.toLowerCase();
  2777. this.metadata[name] = entry.textContent.trim();
  2778. }
  2779. }
  2780. }
  2781. },
  2782. get: function Metadata_get(name) {
  2783. return this.metadata[name] || null;
  2784. },
  2785. has: function Metadata_has(name) {
  2786. return typeof this.metadata[name] !== 'undefined';
  2787. }
  2788. };
  2789. exports.Metadata = Metadata;
  2790. }));
  2791. (function (root, factory) {
  2792. {
  2793. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  2794. }
  2795. }(this, function (exports, sharedUtil) {
  2796. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  2797. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  2798. var ImageKind = sharedUtil.ImageKind;
  2799. var OPS = sharedUtil.OPS;
  2800. var Util = sharedUtil.Util;
  2801. var isNum = sharedUtil.isNum;
  2802. var isArray = sharedUtil.isArray;
  2803. var warn = sharedUtil.warn;
  2804. var createObjectURL = sharedUtil.createObjectURL;
  2805. var SVG_DEFAULTS = {
  2806. fontStyle: 'normal',
  2807. fontWeight: 'normal',
  2808. fillColor: '#000000'
  2809. };
  2810. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  2811. var PNG_HEADER =
  2812. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  2813. var CHUNK_WRAPPER_SIZE = 12;
  2814. var crcTable = new Int32Array(256);
  2815. for (var i = 0; i < 256; i++) {
  2816. var c = i;
  2817. for (var h = 0; h < 8; h++) {
  2818. if (c & 1) {
  2819. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  2820. } else {
  2821. c = (c >> 1) & 0x7fffffff;
  2822. }
  2823. }
  2824. crcTable[i] = c;
  2825. }
  2826. function crc32(data, start, end) {
  2827. var crc = -1;
  2828. for (var i = start; i < end; i++) {
  2829. var a = (crc ^ data[i]) & 0xff;
  2830. var b = crcTable[a];
  2831. crc = (crc >>> 8) ^ b;
  2832. }
  2833. return crc ^ -1;
  2834. }
  2835. function writePngChunk(type, body, data, offset) {
  2836. var p = offset;
  2837. var len = body.length;
  2838. data[p] = len >> 24 & 0xff;
  2839. data[p + 1] = len >> 16 & 0xff;
  2840. data[p + 2] = len >> 8 & 0xff;
  2841. data[p + 3] = len & 0xff;
  2842. p += 4;
  2843. data[p] = type.charCodeAt(0) & 0xff;
  2844. data[p + 1] = type.charCodeAt(1) & 0xff;
  2845. data[p + 2] = type.charCodeAt(2) & 0xff;
  2846. data[p + 3] = type.charCodeAt(3) & 0xff;
  2847. p += 4;
  2848. data.set(body, p);
  2849. p += body.length;
  2850. var crc = crc32(data, offset + 4, p);
  2851. data[p] = crc >> 24 & 0xff;
  2852. data[p + 1] = crc >> 16 & 0xff;
  2853. data[p + 2] = crc >> 8 & 0xff;
  2854. data[p + 3] = crc & 0xff;
  2855. }
  2856. function adler32(data, start, end) {
  2857. var a = 1;
  2858. var b = 0;
  2859. for (var i = start; i < end; ++i) {
  2860. a = (a + (data[i] & 0xff)) % 65521;
  2861. b = (b + a) % 65521;
  2862. }
  2863. return (b << 16) | a;
  2864. }
  2865. function encode(imgData, kind, forceDataSchema) {
  2866. var width = imgData.width;
  2867. var height = imgData.height;
  2868. var bitDepth, colorType, lineSize;
  2869. var bytes = imgData.data;
  2870. switch (kind) {
  2871. case ImageKind.GRAYSCALE_1BPP:
  2872. colorType = 0;
  2873. bitDepth = 1;
  2874. lineSize = (width + 7) >> 3;
  2875. break;
  2876. case ImageKind.RGB_24BPP:
  2877. colorType = 2;
  2878. bitDepth = 8;
  2879. lineSize = width * 3;
  2880. break;
  2881. case ImageKind.RGBA_32BPP:
  2882. colorType = 6;
  2883. bitDepth = 8;
  2884. lineSize = width * 4;
  2885. break;
  2886. default:
  2887. throw new Error('invalid format');
  2888. }
  2889. // prefix every row with predictor 0
  2890. var literals = new Uint8Array((1 + lineSize) * height);
  2891. var offsetLiterals = 0, offsetBytes = 0;
  2892. var y, i;
  2893. for (y = 0; y < height; ++y) {
  2894. literals[offsetLiterals++] = 0; // no prediction
  2895. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  2896. offsetLiterals);
  2897. offsetBytes += lineSize;
  2898. offsetLiterals += lineSize;
  2899. }
  2900. if (kind === ImageKind.GRAYSCALE_1BPP) {
  2901. // inverting for B/W
  2902. offsetLiterals = 0;
  2903. for (y = 0; y < height; y++) {
  2904. offsetLiterals++; // skipping predictor
  2905. for (i = 0; i < lineSize; i++) {
  2906. literals[offsetLiterals++] ^= 0xFF;
  2907. }
  2908. }
  2909. }
  2910. var ihdr = new Uint8Array([
  2911. width >> 24 & 0xff,
  2912. width >> 16 & 0xff,
  2913. width >> 8 & 0xff,
  2914. width & 0xff,
  2915. height >> 24 & 0xff,
  2916. height >> 16 & 0xff,
  2917. height >> 8 & 0xff,
  2918. height & 0xff,
  2919. bitDepth, // bit depth
  2920. colorType, // color type
  2921. 0x00, // compression method
  2922. 0x00, // filter method
  2923. 0x00 // interlace method
  2924. ]);
  2925. var len = literals.length;
  2926. var maxBlockLength = 0xFFFF;
  2927. var deflateBlocks = Math.ceil(len / maxBlockLength);
  2928. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  2929. var pi = 0;
  2930. idat[pi++] = 0x78; // compression method and flags
  2931. idat[pi++] = 0x9c; // flags
  2932. var pos = 0;
  2933. while (len > maxBlockLength) {
  2934. // writing non-final DEFLATE blocks type 0 and length of 65535
  2935. idat[pi++] = 0x00;
  2936. idat[pi++] = 0xff;
  2937. idat[pi++] = 0xff;
  2938. idat[pi++] = 0x00;
  2939. idat[pi++] = 0x00;
  2940. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  2941. pi += maxBlockLength;
  2942. pos += maxBlockLength;
  2943. len -= maxBlockLength;
  2944. }
  2945. // writing non-final DEFLATE blocks type 0
  2946. idat[pi++] = 0x01;
  2947. idat[pi++] = len & 0xff;
  2948. idat[pi++] = len >> 8 & 0xff;
  2949. idat[pi++] = (~len & 0xffff) & 0xff;
  2950. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  2951. idat.set(literals.subarray(pos), pi);
  2952. pi += literals.length - pos;
  2953. var adler = adler32(literals, 0, literals.length); // checksum
  2954. idat[pi++] = adler >> 24 & 0xff;
  2955. idat[pi++] = adler >> 16 & 0xff;
  2956. idat[pi++] = adler >> 8 & 0xff;
  2957. idat[pi++] = adler & 0xff;
  2958. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  2959. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  2960. ihdr.length + idat.length;
  2961. var data = new Uint8Array(pngLength);
  2962. var offset = 0;
  2963. data.set(PNG_HEADER, offset);
  2964. offset += PNG_HEADER.length;
  2965. writePngChunk('IHDR', ihdr, data, offset);
  2966. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  2967. writePngChunk('IDATA', idat, data, offset);
  2968. offset += CHUNK_WRAPPER_SIZE + idat.length;
  2969. writePngChunk('IEND', new Uint8Array(0), data, offset);
  2970. return createObjectURL(data, 'image/png', forceDataSchema);
  2971. }
  2972. return function convertImgDataToPng(imgData, forceDataSchema) {
  2973. var kind = (imgData.kind === undefined ?
  2974. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  2975. return encode(imgData, kind, forceDataSchema);
  2976. };
  2977. })();
  2978. var SVGExtraState = (function SVGExtraStateClosure() {
  2979. function SVGExtraState() {
  2980. this.fontSizeScale = 1;
  2981. this.fontWeight = SVG_DEFAULTS.fontWeight;
  2982. this.fontSize = 0;
  2983. this.textMatrix = IDENTITY_MATRIX;
  2984. this.fontMatrix = FONT_IDENTITY_MATRIX;
  2985. this.leading = 0;
  2986. // Current point (in user coordinates)
  2987. this.x = 0;
  2988. this.y = 0;
  2989. // Start of text line (in text coordinates)
  2990. this.lineX = 0;
  2991. this.lineY = 0;
  2992. // Character and word spacing
  2993. this.charSpacing = 0;
  2994. this.wordSpacing = 0;
  2995. this.textHScale = 1;
  2996. this.textRise = 0;
  2997. // Default foreground and background colors
  2998. this.fillColor = SVG_DEFAULTS.fillColor;
  2999. this.strokeColor = '#000000';
  3000. this.fillAlpha = 1;
  3001. this.strokeAlpha = 1;
  3002. this.lineWidth = 1;
  3003. this.lineJoin = '';
  3004. this.lineCap = '';
  3005. this.miterLimit = 0;
  3006. this.dashArray = [];
  3007. this.dashPhase = 0;
  3008. this.dependencies = [];
  3009. // Clipping
  3010. this.clipId = '';
  3011. this.pendingClip = false;
  3012. this.maskId = '';
  3013. }
  3014. SVGExtraState.prototype = {
  3015. clone: function SVGExtraState_clone() {
  3016. return Object.create(this);
  3017. },
  3018. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3019. this.x = x;
  3020. this.y = y;
  3021. }
  3022. };
  3023. return SVGExtraState;
  3024. })();
  3025. var SVGGraphics = (function SVGGraphicsClosure() {
  3026. function createScratchSVG(width, height) {
  3027. var NS = 'http://www.w3.org/2000/svg';
  3028. var svg = document.createElementNS(NS, 'svg:svg');
  3029. svg.setAttributeNS(null, 'version', '1.1');
  3030. svg.setAttributeNS(null, 'width', width + 'px');
  3031. svg.setAttributeNS(null, 'height', height + 'px');
  3032. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3033. return svg;
  3034. }
  3035. function opListToTree(opList) {
  3036. var opTree = [];
  3037. var tmp = [];
  3038. var opListLen = opList.length;
  3039. for (var x = 0; x < opListLen; x++) {
  3040. if (opList[x].fn === 'save') {
  3041. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3042. tmp.push(opTree);
  3043. opTree = opTree[opTree.length - 1].items;
  3044. continue;
  3045. }
  3046. if(opList[x].fn === 'restore') {
  3047. opTree = tmp.pop();
  3048. } else {
  3049. opTree.push(opList[x]);
  3050. }
  3051. }
  3052. return opTree;
  3053. }
  3054. /**
  3055. * Formats float number.
  3056. * @param value {number} number to format.
  3057. * @returns {string}
  3058. */
  3059. function pf(value) {
  3060. if (value === (value | 0)) { // integer number
  3061. return value.toString();
  3062. }
  3063. var s = value.toFixed(10);
  3064. var i = s.length - 1;
  3065. if (s[i] !== '0') {
  3066. return s;
  3067. }
  3068. // removing trailing zeros
  3069. do {
  3070. i--;
  3071. } while (s[i] === '0');
  3072. return s.substr(0, s[i] === '.' ? i : i + 1);
  3073. }
  3074. /**
  3075. * Formats transform matrix. The standard rotation, scale and translate
  3076. * matrices are replaced by their shorter forms, and for identity matrix
  3077. * returns empty string to save the memory.
  3078. * @param m {Array} matrix to format.
  3079. * @returns {string}
  3080. */
  3081. function pm(m) {
  3082. if (m[4] === 0 && m[5] === 0) {
  3083. if (m[1] === 0 && m[2] === 0) {
  3084. if (m[0] === 1 && m[3] === 1) {
  3085. return '';
  3086. }
  3087. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3088. }
  3089. if (m[0] === m[3] && m[1] === -m[2]) {
  3090. var a = Math.acos(m[0]) * 180 / Math.PI;
  3091. return 'rotate(' + pf(a) + ')';
  3092. }
  3093. } else {
  3094. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3095. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3096. }
  3097. }
  3098. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3099. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3100. }
  3101. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3102. this.current = new SVGExtraState();
  3103. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3104. this.transformStack = [];
  3105. this.extraStack = [];
  3106. this.commonObjs = commonObjs;
  3107. this.objs = objs;
  3108. this.pendingEOFill = false;
  3109. this.embedFonts = false;
  3110. this.embeddedFonts = Object.create(null);
  3111. this.cssStyle = null;
  3112. this.forceDataSchema = !!forceDataSchema;
  3113. }
  3114. var NS = 'http://www.w3.org/2000/svg';
  3115. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3116. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3117. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3118. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3119. var clipCount = 0;
  3120. var maskCount = 0;
  3121. SVGGraphics.prototype = {
  3122. save: function SVGGraphics_save() {
  3123. this.transformStack.push(this.transformMatrix);
  3124. var old = this.current;
  3125. this.extraStack.push(old);
  3126. this.current = old.clone();
  3127. },
  3128. restore: function SVGGraphics_restore() {
  3129. this.transformMatrix = this.transformStack.pop();
  3130. this.current = this.extraStack.pop();
  3131. this.tgrp = document.createElementNS(NS, 'svg:g');
  3132. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3133. this.pgrp.appendChild(this.tgrp);
  3134. },
  3135. group: function SVGGraphics_group(items) {
  3136. this.save();
  3137. this.executeOpTree(items);
  3138. this.restore();
  3139. },
  3140. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3141. var fnArray = operatorList.fnArray;
  3142. var fnArrayLen = fnArray.length;
  3143. var argsArray = operatorList.argsArray;
  3144. var self = this;
  3145. for (var i = 0; i < fnArrayLen; i++) {
  3146. if (OPS.dependency === fnArray[i]) {
  3147. var deps = argsArray[i];
  3148. for (var n = 0, nn = deps.length; n < nn; n++) {
  3149. var obj = deps[n];
  3150. var common = obj.substring(0, 2) === 'g_';
  3151. var promise;
  3152. if (common) {
  3153. promise = new Promise(function(resolve) {
  3154. self.commonObjs.get(obj, resolve);
  3155. });
  3156. } else {
  3157. promise = new Promise(function(resolve) {
  3158. self.objs.get(obj, resolve);
  3159. });
  3160. }
  3161. this.current.dependencies.push(promise);
  3162. }
  3163. }
  3164. }
  3165. return Promise.all(this.current.dependencies);
  3166. },
  3167. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3168. var transformMatrix = [a, b, c, d, e, f];
  3169. this.transformMatrix = Util.transform(this.transformMatrix,
  3170. transformMatrix);
  3171. this.tgrp = document.createElementNS(NS, 'svg:g');
  3172. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3173. },
  3174. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3175. this.svg = createScratchSVG(viewport.width, viewport.height);
  3176. this.viewport = viewport;
  3177. return this.loadDependencies(operatorList).then(function () {
  3178. this.transformMatrix = IDENTITY_MATRIX;
  3179. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3180. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3181. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3182. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3183. this.defs = document.createElementNS(NS, 'svg:defs');
  3184. this.pgrp.appendChild(this.defs);
  3185. this.pgrp.appendChild(this.tgrp);
  3186. this.svg.appendChild(this.pgrp);
  3187. var opTree = this.convertOpList(operatorList);
  3188. this.executeOpTree(opTree);
  3189. return this.svg;
  3190. }.bind(this));
  3191. },
  3192. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3193. var argsArray = operatorList.argsArray;
  3194. var fnArray = operatorList.fnArray;
  3195. var fnArrayLen = fnArray.length;
  3196. var REVOPS = [];
  3197. var opList = [];
  3198. for (var op in OPS) {
  3199. REVOPS[OPS[op]] = op;
  3200. }
  3201. for (var x = 0; x < fnArrayLen; x++) {
  3202. var fnId = fnArray[x];
  3203. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3204. }
  3205. return opListToTree(opList);
  3206. },
  3207. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3208. var opTreeLen = opTree.length;
  3209. for(var x = 0; x < opTreeLen; x++) {
  3210. var fn = opTree[x].fn;
  3211. var fnId = opTree[x].fnId;
  3212. var args = opTree[x].args;
  3213. switch (fnId | 0) {
  3214. case OPS.beginText:
  3215. this.beginText();
  3216. break;
  3217. case OPS.setLeading:
  3218. this.setLeading(args);
  3219. break;
  3220. case OPS.setLeadingMoveText:
  3221. this.setLeadingMoveText(args[0], args[1]);
  3222. break;
  3223. case OPS.setFont:
  3224. this.setFont(args);
  3225. break;
  3226. case OPS.showText:
  3227. this.showText(args[0]);
  3228. break;
  3229. case OPS.showSpacedText:
  3230. this.showText(args[0]);
  3231. break;
  3232. case OPS.endText:
  3233. this.endText();
  3234. break;
  3235. case OPS.moveText:
  3236. this.moveText(args[0], args[1]);
  3237. break;
  3238. case OPS.setCharSpacing:
  3239. this.setCharSpacing(args[0]);
  3240. break;
  3241. case OPS.setWordSpacing:
  3242. this.setWordSpacing(args[0]);
  3243. break;
  3244. case OPS.setHScale:
  3245. this.setHScale(args[0]);
  3246. break;
  3247. case OPS.setTextMatrix:
  3248. this.setTextMatrix(args[0], args[1], args[2],
  3249. args[3], args[4], args[5]);
  3250. break;
  3251. case OPS.setLineWidth:
  3252. this.setLineWidth(args[0]);
  3253. break;
  3254. case OPS.setLineJoin:
  3255. this.setLineJoin(args[0]);
  3256. break;
  3257. case OPS.setLineCap:
  3258. this.setLineCap(args[0]);
  3259. break;
  3260. case OPS.setMiterLimit:
  3261. this.setMiterLimit(args[0]);
  3262. break;
  3263. case OPS.setFillRGBColor:
  3264. this.setFillRGBColor(args[0], args[1], args[2]);
  3265. break;
  3266. case OPS.setStrokeRGBColor:
  3267. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3268. break;
  3269. case OPS.setDash:
  3270. this.setDash(args[0], args[1]);
  3271. break;
  3272. case OPS.setGState:
  3273. this.setGState(args[0]);
  3274. break;
  3275. case OPS.fill:
  3276. this.fill();
  3277. break;
  3278. case OPS.eoFill:
  3279. this.eoFill();
  3280. break;
  3281. case OPS.stroke:
  3282. this.stroke();
  3283. break;
  3284. case OPS.fillStroke:
  3285. this.fillStroke();
  3286. break;
  3287. case OPS.eoFillStroke:
  3288. this.eoFillStroke();
  3289. break;
  3290. case OPS.clip:
  3291. this.clip('nonzero');
  3292. break;
  3293. case OPS.eoClip:
  3294. this.clip('evenodd');
  3295. break;
  3296. case OPS.paintSolidColorImageMask:
  3297. this.paintSolidColorImageMask();
  3298. break;
  3299. case OPS.paintJpegXObject:
  3300. this.paintJpegXObject(args[0], args[1], args[2]);
  3301. break;
  3302. case OPS.paintImageXObject:
  3303. this.paintImageXObject(args[0]);
  3304. break;
  3305. case OPS.paintInlineImageXObject:
  3306. this.paintInlineImageXObject(args[0]);
  3307. break;
  3308. case OPS.paintImageMaskXObject:
  3309. this.paintImageMaskXObject(args[0]);
  3310. break;
  3311. case OPS.paintFormXObjectBegin:
  3312. this.paintFormXObjectBegin(args[0], args[1]);
  3313. break;
  3314. case OPS.paintFormXObjectEnd:
  3315. this.paintFormXObjectEnd();
  3316. break;
  3317. case OPS.closePath:
  3318. this.closePath();
  3319. break;
  3320. case OPS.closeStroke:
  3321. this.closeStroke();
  3322. break;
  3323. case OPS.closeFillStroke:
  3324. this.closeFillStroke();
  3325. break;
  3326. case OPS.nextLine:
  3327. this.nextLine();
  3328. break;
  3329. case OPS.transform:
  3330. this.transform(args[0], args[1], args[2], args[3],
  3331. args[4], args[5]);
  3332. break;
  3333. case OPS.constructPath:
  3334. this.constructPath(args[0], args[1]);
  3335. break;
  3336. case OPS.endPath:
  3337. this.endPath();
  3338. break;
  3339. case 92:
  3340. this.group(opTree[x].items);
  3341. break;
  3342. default:
  3343. warn('Unimplemented method '+ fn);
  3344. break;
  3345. }
  3346. }
  3347. },
  3348. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3349. this.current.wordSpacing = wordSpacing;
  3350. },
  3351. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3352. this.current.charSpacing = charSpacing;
  3353. },
  3354. nextLine: function SVGGraphics_nextLine() {
  3355. this.moveText(0, this.current.leading);
  3356. },
  3357. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3358. var current = this.current;
  3359. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  3360. this.current.x = this.current.lineX = 0;
  3361. this.current.y = this.current.lineY = 0;
  3362. current.xcoords = [];
  3363. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3364. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3365. current.tspan.setAttributeNS(null, 'font-size',
  3366. pf(current.fontSize) + 'px');
  3367. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3368. current.txtElement = document.createElementNS(NS, 'svg:text');
  3369. current.txtElement.appendChild(current.tspan);
  3370. },
  3371. beginText: function SVGGraphics_beginText() {
  3372. this.current.x = this.current.lineX = 0;
  3373. this.current.y = this.current.lineY = 0;
  3374. this.current.textMatrix = IDENTITY_MATRIX;
  3375. this.current.lineMatrix = IDENTITY_MATRIX;
  3376. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3377. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3378. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3379. this.current.xcoords = [];
  3380. },
  3381. moveText: function SVGGraphics_moveText(x, y) {
  3382. var current = this.current;
  3383. this.current.x = this.current.lineX += x;
  3384. this.current.y = this.current.lineY += y;
  3385. current.xcoords = [];
  3386. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3387. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3388. current.tspan.setAttributeNS(null, 'font-size',
  3389. pf(current.fontSize) + 'px');
  3390. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3391. },
  3392. showText: function SVGGraphics_showText(glyphs) {
  3393. var current = this.current;
  3394. var font = current.font;
  3395. var fontSize = current.fontSize;
  3396. if (fontSize === 0) {
  3397. return;
  3398. }
  3399. var charSpacing = current.charSpacing;
  3400. var wordSpacing = current.wordSpacing;
  3401. var fontDirection = current.fontDirection;
  3402. var textHScale = current.textHScale * fontDirection;
  3403. var glyphsLength = glyphs.length;
  3404. var vertical = font.vertical;
  3405. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3406. var x = 0, i;
  3407. for (i = 0; i < glyphsLength; ++i) {
  3408. var glyph = glyphs[i];
  3409. if (glyph === null) {
  3410. // word break
  3411. x += fontDirection * wordSpacing;
  3412. continue;
  3413. } else if (isNum(glyph)) {
  3414. x += -glyph * fontSize * 0.001;
  3415. continue;
  3416. }
  3417. current.xcoords.push(current.x + x * textHScale);
  3418. var width = glyph.width;
  3419. var character = glyph.fontChar;
  3420. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3421. x += charWidth;
  3422. current.tspan.textContent += character;
  3423. }
  3424. if (vertical) {
  3425. current.y -= x * textHScale;
  3426. } else {
  3427. current.x += x * textHScale;
  3428. }
  3429. current.tspan.setAttributeNS(null, 'x',
  3430. current.xcoords.map(pf).join(' '));
  3431. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3432. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3433. current.tspan.setAttributeNS(null, 'font-size',
  3434. pf(current.fontSize) + 'px');
  3435. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3436. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3437. }
  3438. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3439. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3440. }
  3441. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3442. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3443. }
  3444. current.txtElement.setAttributeNS(null, 'transform',
  3445. pm(current.textMatrix) +
  3446. ' scale(1, -1)' );
  3447. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3448. current.txtElement.appendChild(current.tspan);
  3449. current.txtgrp.appendChild(current.txtElement);
  3450. this.tgrp.appendChild(current.txtElement);
  3451. },
  3452. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3453. this.setLeading(-y);
  3454. this.moveText(x, y);
  3455. },
  3456. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3457. if (!this.cssStyle) {
  3458. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3459. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3460. this.defs.appendChild(this.cssStyle);
  3461. }
  3462. var url = createObjectURL(fontObj.data, fontObj.mimetype,
  3463. this.forceDataSchema);
  3464. this.cssStyle.textContent +=
  3465. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  3466. ' src: url(' + url + '); }\n';
  3467. },
  3468. setFont: function SVGGraphics_setFont(details) {
  3469. var current = this.current;
  3470. var fontObj = this.commonObjs.get(details[0]);
  3471. var size = details[1];
  3472. this.current.font = fontObj;
  3473. if (this.embedFonts && fontObj.data &&
  3474. !this.embeddedFonts[fontObj.loadedName]) {
  3475. this.addFontStyle(fontObj);
  3476. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3477. }
  3478. current.fontMatrix = (fontObj.fontMatrix ?
  3479. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3480. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3481. (fontObj.bold ? 'bold' : 'normal');
  3482. var italic = fontObj.italic ? 'italic' : 'normal';
  3483. if (size < 0) {
  3484. size = -size;
  3485. current.fontDirection = -1;
  3486. } else {
  3487. current.fontDirection = 1;
  3488. }
  3489. current.fontSize = size;
  3490. current.fontFamily = fontObj.loadedName;
  3491. current.fontWeight = bold;
  3492. current.fontStyle = italic;
  3493. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3494. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3495. current.xcoords = [];
  3496. },
  3497. endText: function SVGGraphics_endText() {
  3498. if (this.current.pendingClip) {
  3499. this.cgrp.appendChild(this.tgrp);
  3500. this.pgrp.appendChild(this.cgrp);
  3501. } else {
  3502. this.pgrp.appendChild(this.tgrp);
  3503. }
  3504. this.tgrp = document.createElementNS(NS, 'svg:g');
  3505. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3506. },
  3507. // Path properties
  3508. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3509. this.current.lineWidth = width;
  3510. },
  3511. setLineCap: function SVGGraphics_setLineCap(style) {
  3512. this.current.lineCap = LINE_CAP_STYLES[style];
  3513. },
  3514. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3515. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3516. },
  3517. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3518. this.current.miterLimit = limit;
  3519. },
  3520. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3521. var color = Util.makeCssRgb(r, g, b);
  3522. this.current.strokeColor = color;
  3523. },
  3524. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3525. var color = Util.makeCssRgb(r, g, b);
  3526. this.current.fillColor = color;
  3527. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3528. this.current.xcoords = [];
  3529. },
  3530. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3531. this.current.dashArray = dashArray;
  3532. this.current.dashPhase = dashPhase;
  3533. },
  3534. constructPath: function SVGGraphics_constructPath(ops, args) {
  3535. var current = this.current;
  3536. var x = current.x, y = current.y;
  3537. current.path = document.createElementNS(NS, 'svg:path');
  3538. var d = [];
  3539. var opLength = ops.length;
  3540. for (var i = 0, j = 0; i < opLength; i++) {
  3541. switch (ops[i] | 0) {
  3542. case OPS.rectangle:
  3543. x = args[j++];
  3544. y = args[j++];
  3545. var width = args[j++];
  3546. var height = args[j++];
  3547. var xw = x + width;
  3548. var yh = y + height;
  3549. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  3550. 'L', pf(x), pf(yh), 'Z');
  3551. break;
  3552. case OPS.moveTo:
  3553. x = args[j++];
  3554. y = args[j++];
  3555. d.push('M', pf(x), pf(y));
  3556. break;
  3557. case OPS.lineTo:
  3558. x = args[j++];
  3559. y = args[j++];
  3560. d.push('L', pf(x) , pf(y));
  3561. break;
  3562. case OPS.curveTo:
  3563. x = args[j + 4];
  3564. y = args[j + 5];
  3565. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  3566. pf(args[j + 3]), pf(x), pf(y));
  3567. j += 6;
  3568. break;
  3569. case OPS.curveTo2:
  3570. x = args[j + 2];
  3571. y = args[j + 3];
  3572. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  3573. pf(args[j + 2]), pf(args[j + 3]));
  3574. j += 4;
  3575. break;
  3576. case OPS.curveTo3:
  3577. x = args[j + 2];
  3578. y = args[j + 3];
  3579. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  3580. pf(x), pf(y));
  3581. j += 4;
  3582. break;
  3583. case OPS.closePath:
  3584. d.push('Z');
  3585. break;
  3586. }
  3587. }
  3588. current.path.setAttributeNS(null, 'd', d.join(' '));
  3589. current.path.setAttributeNS(null, 'stroke-miterlimit',
  3590. pf(current.miterLimit));
  3591. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3592. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3593. current.path.setAttributeNS(null, 'stroke-width',
  3594. pf(current.lineWidth) + 'px');
  3595. current.path.setAttributeNS(null, 'stroke-dasharray',
  3596. current.dashArray.map(pf).join(' '));
  3597. current.path.setAttributeNS(null, 'stroke-dashoffset',
  3598. pf(current.dashPhase) + 'px');
  3599. current.path.setAttributeNS(null, 'fill', 'none');
  3600. this.tgrp.appendChild(current.path);
  3601. if (current.pendingClip) {
  3602. this.cgrp.appendChild(this.tgrp);
  3603. this.pgrp.appendChild(this.cgrp);
  3604. } else {
  3605. this.pgrp.appendChild(this.tgrp);
  3606. }
  3607. // Saving a reference in current.element so that it can be addressed
  3608. // in 'fill' and 'stroke'
  3609. current.element = current.path;
  3610. current.setCurrentPoint(x, y);
  3611. },
  3612. endPath: function SVGGraphics_endPath() {
  3613. var current = this.current;
  3614. if (current.pendingClip) {
  3615. this.cgrp.appendChild(this.tgrp);
  3616. this.pgrp.appendChild(this.cgrp);
  3617. } else {
  3618. this.pgrp.appendChild(this.tgrp);
  3619. }
  3620. this.tgrp = document.createElementNS(NS, 'svg:g');
  3621. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3622. },
  3623. clip: function SVGGraphics_clip(type) {
  3624. var current = this.current;
  3625. // Add current path to clipping path
  3626. current.clipId = 'clippath' + clipCount;
  3627. clipCount++;
  3628. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3629. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3630. var clipElement = current.element.cloneNode();
  3631. if (type === 'evenodd') {
  3632. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3633. } else {
  3634. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3635. }
  3636. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3637. this.clippath.appendChild(clipElement);
  3638. this.defs.appendChild(this.clippath);
  3639. // Create a new group with that attribute
  3640. current.pendingClip = true;
  3641. this.cgrp = document.createElementNS(NS, 'svg:g');
  3642. this.cgrp.setAttributeNS(null, 'clip-path',
  3643. 'url(#' + current.clipId + ')');
  3644. this.pgrp.appendChild(this.cgrp);
  3645. },
  3646. closePath: function SVGGraphics_closePath() {
  3647. var current = this.current;
  3648. var d = current.path.getAttributeNS(null, 'd');
  3649. d += 'Z';
  3650. current.path.setAttributeNS(null, 'd', d);
  3651. },
  3652. setLeading: function SVGGraphics_setLeading(leading) {
  3653. this.current.leading = -leading;
  3654. },
  3655. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3656. this.current.textRise = textRise;
  3657. },
  3658. setHScale: function SVGGraphics_setHScale(scale) {
  3659. this.current.textHScale = scale / 100;
  3660. },
  3661. setGState: function SVGGraphics_setGState(states) {
  3662. for (var i = 0, ii = states.length; i < ii; i++) {
  3663. var state = states[i];
  3664. var key = state[0];
  3665. var value = state[1];
  3666. switch (key) {
  3667. case 'LW':
  3668. this.setLineWidth(value);
  3669. break;
  3670. case 'LC':
  3671. this.setLineCap(value);
  3672. break;
  3673. case 'LJ':
  3674. this.setLineJoin(value);
  3675. break;
  3676. case 'ML':
  3677. this.setMiterLimit(value);
  3678. break;
  3679. case 'D':
  3680. this.setDash(value[0], value[1]);
  3681. break;
  3682. case 'RI':
  3683. break;
  3684. case 'FL':
  3685. break;
  3686. case 'Font':
  3687. this.setFont(value);
  3688. break;
  3689. case 'CA':
  3690. break;
  3691. case 'ca':
  3692. break;
  3693. case 'BM':
  3694. break;
  3695. case 'SMask':
  3696. break;
  3697. }
  3698. }
  3699. },
  3700. fill: function SVGGraphics_fill() {
  3701. var current = this.current;
  3702. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3703. },
  3704. stroke: function SVGGraphics_stroke() {
  3705. var current = this.current;
  3706. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3707. current.element.setAttributeNS(null, 'fill', 'none');
  3708. },
  3709. eoFill: function SVGGraphics_eoFill() {
  3710. var current = this.current;
  3711. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3712. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3713. },
  3714. fillStroke: function SVGGraphics_fillStroke() {
  3715. // Order is important since stroke wants fill to be none.
  3716. // First stroke, then if fill needed, it will be overwritten.
  3717. this.stroke();
  3718. this.fill();
  3719. },
  3720. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3721. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3722. this.fillStroke();
  3723. },
  3724. closeStroke: function SVGGraphics_closeStroke() {
  3725. this.closePath();
  3726. this.stroke();
  3727. },
  3728. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3729. this.closePath();
  3730. this.fillStroke();
  3731. },
  3732. paintSolidColorImageMask:
  3733. function SVGGraphics_paintSolidColorImageMask() {
  3734. var current = this.current;
  3735. var rect = document.createElementNS(NS, 'svg:rect');
  3736. rect.setAttributeNS(null, 'x', '0');
  3737. rect.setAttributeNS(null, 'y', '0');
  3738. rect.setAttributeNS(null, 'width', '1px');
  3739. rect.setAttributeNS(null, 'height', '1px');
  3740. rect.setAttributeNS(null, 'fill', current.fillColor);
  3741. this.tgrp.appendChild(rect);
  3742. },
  3743. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3744. var current = this.current;
  3745. var imgObj = this.objs.get(objId);
  3746. var imgEl = document.createElementNS(NS, 'svg:image');
  3747. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3748. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3749. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3750. imgEl.setAttributeNS(null, 'x', '0');
  3751. imgEl.setAttributeNS(null, 'y', pf(-h));
  3752. imgEl.setAttributeNS(null, 'transform',
  3753. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3754. this.tgrp.appendChild(imgEl);
  3755. if (current.pendingClip) {
  3756. this.cgrp.appendChild(this.tgrp);
  3757. this.pgrp.appendChild(this.cgrp);
  3758. } else {
  3759. this.pgrp.appendChild(this.tgrp);
  3760. }
  3761. },
  3762. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3763. var imgData = this.objs.get(objId);
  3764. if (!imgData) {
  3765. warn('Dependent image isn\'t ready yet');
  3766. return;
  3767. }
  3768. this.paintInlineImageXObject(imgData);
  3769. },
  3770. paintInlineImageXObject:
  3771. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3772. var current = this.current;
  3773. var width = imgData.width;
  3774. var height = imgData.height;
  3775. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3776. var cliprect = document.createElementNS(NS, 'svg:rect');
  3777. cliprect.setAttributeNS(null, 'x', '0');
  3778. cliprect.setAttributeNS(null, 'y', '0');
  3779. cliprect.setAttributeNS(null, 'width', pf(width));
  3780. cliprect.setAttributeNS(null, 'height', pf(height));
  3781. current.element = cliprect;
  3782. this.clip('nonzero');
  3783. var imgEl = document.createElementNS(NS, 'svg:image');
  3784. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  3785. imgEl.setAttributeNS(null, 'x', '0');
  3786. imgEl.setAttributeNS(null, 'y', pf(-height));
  3787. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  3788. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  3789. imgEl.setAttributeNS(null, 'transform',
  3790. 'scale(' + pf(1 / width) + ' ' +
  3791. pf(-1 / height) + ')');
  3792. if (mask) {
  3793. mask.appendChild(imgEl);
  3794. } else {
  3795. this.tgrp.appendChild(imgEl);
  3796. }
  3797. if (current.pendingClip) {
  3798. this.cgrp.appendChild(this.tgrp);
  3799. this.pgrp.appendChild(this.cgrp);
  3800. } else {
  3801. this.pgrp.appendChild(this.tgrp);
  3802. }
  3803. },
  3804. paintImageMaskXObject:
  3805. function SVGGraphics_paintImageMaskXObject(imgData) {
  3806. var current = this.current;
  3807. var width = imgData.width;
  3808. var height = imgData.height;
  3809. var fillColor = current.fillColor;
  3810. current.maskId = 'mask' + maskCount++;
  3811. var mask = document.createElementNS(NS, 'svg:mask');
  3812. mask.setAttributeNS(null, 'id', current.maskId);
  3813. var rect = document.createElementNS(NS, 'svg:rect');
  3814. rect.setAttributeNS(null, 'x', '0');
  3815. rect.setAttributeNS(null, 'y', '0');
  3816. rect.setAttributeNS(null, 'width', pf(width));
  3817. rect.setAttributeNS(null, 'height', pf(height));
  3818. rect.setAttributeNS(null, 'fill', fillColor);
  3819. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  3820. this.defs.appendChild(mask);
  3821. this.tgrp.appendChild(rect);
  3822. this.paintInlineImageXObject(imgData, mask);
  3823. },
  3824. paintFormXObjectBegin:
  3825. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  3826. this.save();
  3827. if (isArray(matrix) && matrix.length === 6) {
  3828. this.transform(matrix[0], matrix[1], matrix[2],
  3829. matrix[3], matrix[4], matrix[5]);
  3830. }
  3831. if (isArray(bbox) && bbox.length === 4) {
  3832. var width = bbox[2] - bbox[0];
  3833. var height = bbox[3] - bbox[1];
  3834. var cliprect = document.createElementNS(NS, 'svg:rect');
  3835. cliprect.setAttributeNS(null, 'x', bbox[0]);
  3836. cliprect.setAttributeNS(null, 'y', bbox[1]);
  3837. cliprect.setAttributeNS(null, 'width', pf(width));
  3838. cliprect.setAttributeNS(null, 'height', pf(height));
  3839. this.current.element = cliprect;
  3840. this.clip('nonzero');
  3841. this.endPath();
  3842. }
  3843. },
  3844. paintFormXObjectEnd:
  3845. function SVGGraphics_paintFormXObjectEnd() {
  3846. this.restore();
  3847. }
  3848. };
  3849. return SVGGraphics;
  3850. })();
  3851. exports.SVGGraphics = SVGGraphics;
  3852. }));
  3853. (function (root, factory) {
  3854. {
  3855. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  3856. root.pdfjsDisplayDOMUtils);
  3857. }
  3858. }(this, function (exports, sharedUtil, displayDOMUtils) {
  3859. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  3860. var AnnotationType = sharedUtil.AnnotationType;
  3861. var Util = sharedUtil.Util;
  3862. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  3863. var LinkTarget = displayDOMUtils.LinkTarget;
  3864. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  3865. var warn = sharedUtil.warn;
  3866. var CustomStyle = displayDOMUtils.CustomStyle;
  3867. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  3868. /**
  3869. * @typedef {Object} AnnotationElementParameters
  3870. * @property {Object} data
  3871. * @property {HTMLDivElement} layer
  3872. * @property {PDFPage} page
  3873. * @property {PageViewport} viewport
  3874. * @property {IPDFLinkService} linkService
  3875. * @property {DownloadManager} downloadManager
  3876. */
  3877. /**
  3878. * @class
  3879. * @alias AnnotationElementFactory
  3880. */
  3881. function AnnotationElementFactory() {}
  3882. AnnotationElementFactory.prototype =
  3883. /** @lends AnnotationElementFactory.prototype */ {
  3884. /**
  3885. * @param {AnnotationElementParameters} parameters
  3886. * @returns {AnnotationElement}
  3887. */
  3888. create: function AnnotationElementFactory_create(parameters) {
  3889. var subtype = parameters.data.annotationType;
  3890. switch (subtype) {
  3891. case AnnotationType.LINK:
  3892. return new LinkAnnotationElement(parameters);
  3893. case AnnotationType.TEXT:
  3894. return new TextAnnotationElement(parameters);
  3895. case AnnotationType.WIDGET:
  3896. var fieldType = parameters.data.fieldType;
  3897. switch (fieldType) {
  3898. case 'Tx':
  3899. return new TextWidgetAnnotationElement(parameters);
  3900. }
  3901. return new WidgetAnnotationElement(parameters);
  3902. case AnnotationType.POPUP:
  3903. return new PopupAnnotationElement(parameters);
  3904. case AnnotationType.HIGHLIGHT:
  3905. return new HighlightAnnotationElement(parameters);
  3906. case AnnotationType.UNDERLINE:
  3907. return new UnderlineAnnotationElement(parameters);
  3908. case AnnotationType.SQUIGGLY:
  3909. return new SquigglyAnnotationElement(parameters);
  3910. case AnnotationType.STRIKEOUT:
  3911. return new StrikeOutAnnotationElement(parameters);
  3912. case AnnotationType.FILEATTACHMENT:
  3913. return new FileAttachmentAnnotationElement(parameters);
  3914. default:
  3915. return new AnnotationElement(parameters);
  3916. }
  3917. }
  3918. };
  3919. /**
  3920. * @class
  3921. * @alias AnnotationElement
  3922. */
  3923. var AnnotationElement = (function AnnotationElementClosure() {
  3924. function AnnotationElement(parameters, isRenderable) {
  3925. this.isRenderable = isRenderable || false;
  3926. this.data = parameters.data;
  3927. this.layer = parameters.layer;
  3928. this.page = parameters.page;
  3929. this.viewport = parameters.viewport;
  3930. this.linkService = parameters.linkService;
  3931. this.downloadManager = parameters.downloadManager;
  3932. this.imageResourcesPath = parameters.imageResourcesPath;
  3933. if (isRenderable) {
  3934. this.container = this._createContainer();
  3935. }
  3936. }
  3937. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  3938. /**
  3939. * Create an empty container for the annotation's HTML element.
  3940. *
  3941. * @private
  3942. * @memberof AnnotationElement
  3943. * @returns {HTMLSectionElement}
  3944. */
  3945. _createContainer: function AnnotationElement_createContainer() {
  3946. var data = this.data, page = this.page, viewport = this.viewport;
  3947. var container = document.createElement('section');
  3948. var width = data.rect[2] - data.rect[0];
  3949. var height = data.rect[3] - data.rect[1];
  3950. container.setAttribute('data-annotation-id', data.id);
  3951. // Do *not* modify `data.rect`, since that will corrupt the annotation
  3952. // position on subsequent calls to `_createContainer` (see issue 6804).
  3953. var rect = Util.normalizeRect([
  3954. data.rect[0],
  3955. page.view[3] - data.rect[1] + page.view[1],
  3956. data.rect[2],
  3957. page.view[3] - data.rect[3] + page.view[1]
  3958. ]);
  3959. CustomStyle.setProp('transform', container,
  3960. 'matrix(' + viewport.transform.join(',') + ')');
  3961. CustomStyle.setProp('transformOrigin', container,
  3962. -rect[0] + 'px ' + -rect[1] + 'px');
  3963. if (data.borderStyle.width > 0) {
  3964. container.style.borderWidth = data.borderStyle.width + 'px';
  3965. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  3966. // Underline styles only have a bottom border, so we do not need
  3967. // to adjust for all borders. This yields a similar result as
  3968. // Adobe Acrobat/Reader.
  3969. width = width - 2 * data.borderStyle.width;
  3970. height = height - 2 * data.borderStyle.width;
  3971. }
  3972. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  3973. var verticalRadius = data.borderStyle.verticalCornerRadius;
  3974. if (horizontalRadius > 0 || verticalRadius > 0) {
  3975. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  3976. CustomStyle.setProp('borderRadius', container, radius);
  3977. }
  3978. switch (data.borderStyle.style) {
  3979. case AnnotationBorderStyleType.SOLID:
  3980. container.style.borderStyle = 'solid';
  3981. break;
  3982. case AnnotationBorderStyleType.DASHED:
  3983. container.style.borderStyle = 'dashed';
  3984. break;
  3985. case AnnotationBorderStyleType.BEVELED:
  3986. warn('Unimplemented border style: beveled');
  3987. break;
  3988. case AnnotationBorderStyleType.INSET:
  3989. warn('Unimplemented border style: inset');
  3990. break;
  3991. case AnnotationBorderStyleType.UNDERLINE:
  3992. container.style.borderBottomStyle = 'solid';
  3993. break;
  3994. default:
  3995. break;
  3996. }
  3997. if (data.color) {
  3998. container.style.borderColor =
  3999. Util.makeCssRgb(data.color[0] | 0,
  4000. data.color[1] | 0,
  4001. data.color[2] | 0);
  4002. } else {
  4003. // Transparent (invisible) border, so do not draw it at all.
  4004. container.style.borderWidth = 0;
  4005. }
  4006. }
  4007. container.style.left = rect[0] + 'px';
  4008. container.style.top = rect[1] + 'px';
  4009. container.style.width = width + 'px';
  4010. container.style.height = height + 'px';
  4011. return container;
  4012. },
  4013. /**
  4014. * Create a popup for the annotation's HTML element. This is used for
  4015. * annotations that do not have a Popup entry in the dictionary, but
  4016. * are of a type that works with popups (such as Highlight annotations).
  4017. *
  4018. * @private
  4019. * @param {HTMLSectionElement} container
  4020. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4021. * @param {Object} data
  4022. * @memberof AnnotationElement
  4023. */
  4024. _createPopup:
  4025. function AnnotationElement_createPopup(container, trigger, data) {
  4026. // If no trigger element is specified, create it.
  4027. if (!trigger) {
  4028. trigger = document.createElement('div');
  4029. trigger.style.height = container.style.height;
  4030. trigger.style.width = container.style.width;
  4031. container.appendChild(trigger);
  4032. }
  4033. var popupElement = new PopupElement({
  4034. container: container,
  4035. trigger: trigger,
  4036. color: data.color,
  4037. title: data.title,
  4038. contents: data.contents,
  4039. hideWrapper: true
  4040. });
  4041. var popup = popupElement.render();
  4042. // Position the popup next to the annotation's container.
  4043. popup.style.left = container.style.width;
  4044. container.appendChild(popup);
  4045. },
  4046. /**
  4047. * Render the annotation's HTML element in the empty container.
  4048. *
  4049. * @public
  4050. * @memberof AnnotationElement
  4051. */
  4052. render: function AnnotationElement_render() {
  4053. throw new Error('Abstract method AnnotationElement.render called');
  4054. }
  4055. };
  4056. return AnnotationElement;
  4057. })();
  4058. /**
  4059. * @class
  4060. * @alias LinkAnnotationElement
  4061. */
  4062. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  4063. function LinkAnnotationElement(parameters) {
  4064. AnnotationElement.call(this, parameters, true);
  4065. }
  4066. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4067. /**
  4068. * Render the link annotation's HTML element in the empty container.
  4069. *
  4070. * @public
  4071. * @memberof LinkAnnotationElement
  4072. * @returns {HTMLSectionElement}
  4073. */
  4074. render: function LinkAnnotationElement_render() {
  4075. this.container.className = 'linkAnnotation';
  4076. var link = document.createElement('a');
  4077. addLinkAttributes(link, {
  4078. url: this.data.url,
  4079. target: (this.data.newWindow ? LinkTarget.BLANK : undefined),
  4080. });
  4081. if (!this.data.url) {
  4082. if (this.data.action) {
  4083. this._bindNamedAction(link, this.data.action);
  4084. } else {
  4085. this._bindLink(link, (this.data.dest || null));
  4086. }
  4087. }
  4088. this.container.appendChild(link);
  4089. return this.container;
  4090. },
  4091. /**
  4092. * Bind internal links to the link element.
  4093. *
  4094. * @private
  4095. * @param {Object} link
  4096. * @param {Object} destination
  4097. * @memberof LinkAnnotationElement
  4098. */
  4099. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4100. var self = this;
  4101. link.href = this.linkService.getDestinationHash(destination);
  4102. link.onclick = function() {
  4103. if (destination) {
  4104. self.linkService.navigateTo(destination);
  4105. }
  4106. return false;
  4107. };
  4108. if (destination) {
  4109. link.className = 'internalLink';
  4110. }
  4111. },
  4112. /**
  4113. * Bind named actions to the link element.
  4114. *
  4115. * @private
  4116. * @param {Object} link
  4117. * @param {Object} action
  4118. * @memberof LinkAnnotationElement
  4119. */
  4120. _bindNamedAction:
  4121. function LinkAnnotationElement_bindNamedAction(link, action) {
  4122. var self = this;
  4123. link.href = this.linkService.getAnchorUrl('');
  4124. link.onclick = function() {
  4125. self.linkService.executeNamedAction(action);
  4126. return false;
  4127. };
  4128. link.className = 'internalLink';
  4129. }
  4130. });
  4131. return LinkAnnotationElement;
  4132. })();
  4133. /**
  4134. * @class
  4135. * @alias TextAnnotationElement
  4136. */
  4137. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  4138. function TextAnnotationElement(parameters) {
  4139. var isRenderable = !!(parameters.data.hasPopup ||
  4140. parameters.data.title || parameters.data.contents);
  4141. AnnotationElement.call(this, parameters, isRenderable);
  4142. }
  4143. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4144. /**
  4145. * Render the text annotation's HTML element in the empty container.
  4146. *
  4147. * @public
  4148. * @memberof TextAnnotationElement
  4149. * @returns {HTMLSectionElement}
  4150. */
  4151. render: function TextAnnotationElement_render() {
  4152. this.container.className = 'textAnnotation';
  4153. var image = document.createElement('img');
  4154. image.style.height = this.container.style.height;
  4155. image.style.width = this.container.style.width;
  4156. image.src = this.imageResourcesPath + 'annotation-' +
  4157. this.data.name.toLowerCase() + '.svg';
  4158. image.alt = '[{{type}} Annotation]';
  4159. image.dataset.l10nId = 'text_annotation_type';
  4160. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  4161. if (!this.data.hasPopup) {
  4162. this._createPopup(this.container, image, this.data);
  4163. }
  4164. this.container.appendChild(image);
  4165. return this.container;
  4166. }
  4167. });
  4168. return TextAnnotationElement;
  4169. })();
  4170. /**
  4171. * @class
  4172. * @alias WidgetAnnotationElement
  4173. */
  4174. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  4175. function WidgetAnnotationElement(parameters) {
  4176. AnnotationElement.call(this, parameters, true);
  4177. }
  4178. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4179. /**
  4180. * Render the widget annotation's HTML element in the empty container.
  4181. *
  4182. * @public
  4183. * @memberof WidgetAnnotationElement
  4184. * @returns {HTMLSectionElement}
  4185. */
  4186. render: function WidgetAnnotationElement_render() {
  4187. // Show only the container for unsupported field types.
  4188. return this.container;
  4189. }
  4190. });
  4191. return WidgetAnnotationElement;
  4192. })();
  4193. /**
  4194. * @class
  4195. * @alias TextWidgetAnnotationElement
  4196. */
  4197. var TextWidgetAnnotationElement = (
  4198. function TextWidgetAnnotationElementClosure() {
  4199. function TextWidgetAnnotationElement(parameters) {
  4200. WidgetAnnotationElement.call(this, parameters);
  4201. }
  4202. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4203. /**
  4204. * Render the text widget annotation's HTML element in the empty container.
  4205. *
  4206. * @public
  4207. * @memberof TextWidgetAnnotationElement
  4208. * @returns {HTMLSectionElement}
  4209. */
  4210. render: function TextWidgetAnnotationElement_render() {
  4211. var content = document.createElement('div');
  4212. content.textContent = this.data.fieldValue;
  4213. var textAlignment = this.data.textAlignment;
  4214. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  4215. content.style.verticalAlign = 'middle';
  4216. content.style.display = 'table-cell';
  4217. var font = (this.data.fontRefName ?
  4218. this.page.commonObjs.getData(this.data.fontRefName) : null);
  4219. this._setTextStyle(content, font);
  4220. this.container.appendChild(content);
  4221. return this.container;
  4222. },
  4223. /**
  4224. * Apply text styles to the text in the element.
  4225. *
  4226. * @private
  4227. * @param {HTMLDivElement} element
  4228. * @param {Object} font
  4229. * @memberof TextWidgetAnnotationElement
  4230. */
  4231. _setTextStyle:
  4232. function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4233. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4234. var style = element.style;
  4235. style.fontSize = this.data.fontSize + 'px';
  4236. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  4237. if (!font) {
  4238. return;
  4239. }
  4240. style.fontWeight = (font.black ?
  4241. (font.bold ? '900' : 'bold') :
  4242. (font.bold ? 'bold' : 'normal'));
  4243. style.fontStyle = (font.italic ? 'italic' : 'normal');
  4244. // Use a reasonable default font if the font doesn't specify a fallback.
  4245. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4246. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4247. style.fontFamily = fontFamily + fallbackName;
  4248. }
  4249. });
  4250. return TextWidgetAnnotationElement;
  4251. })();
  4252. /**
  4253. * @class
  4254. * @alias PopupAnnotationElement
  4255. */
  4256. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  4257. function PopupAnnotationElement(parameters) {
  4258. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4259. AnnotationElement.call(this, parameters, isRenderable);
  4260. }
  4261. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4262. /**
  4263. * Render the popup annotation's HTML element in the empty container.
  4264. *
  4265. * @public
  4266. * @memberof PopupAnnotationElement
  4267. * @returns {HTMLSectionElement}
  4268. */
  4269. render: function PopupAnnotationElement_render() {
  4270. this.container.className = 'popupAnnotation';
  4271. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4272. var parentElement = this.layer.querySelector(selector);
  4273. if (!parentElement) {
  4274. return this.container;
  4275. }
  4276. var popup = new PopupElement({
  4277. container: this.container,
  4278. trigger: parentElement,
  4279. color: this.data.color,
  4280. title: this.data.title,
  4281. contents: this.data.contents
  4282. });
  4283. // Position the popup next to the parent annotation's container.
  4284. // PDF viewers ignore a popup annotation's rectangle.
  4285. var parentLeft = parseFloat(parentElement.style.left);
  4286. var parentWidth = parseFloat(parentElement.style.width);
  4287. CustomStyle.setProp('transformOrigin', this.container,
  4288. -(parentLeft + parentWidth) + 'px -' +
  4289. parentElement.style.top);
  4290. this.container.style.left = (parentLeft + parentWidth) + 'px';
  4291. this.container.appendChild(popup.render());
  4292. return this.container;
  4293. }
  4294. });
  4295. return PopupAnnotationElement;
  4296. })();
  4297. /**
  4298. * @class
  4299. * @alias PopupElement
  4300. */
  4301. var PopupElement = (function PopupElementClosure() {
  4302. var BACKGROUND_ENLIGHT = 0.7;
  4303. function PopupElement(parameters) {
  4304. this.container = parameters.container;
  4305. this.trigger = parameters.trigger;
  4306. this.color = parameters.color;
  4307. this.title = parameters.title;
  4308. this.contents = parameters.contents;
  4309. this.hideWrapper = parameters.hideWrapper || false;
  4310. this.pinned = false;
  4311. }
  4312. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  4313. /**
  4314. * Render the popup's HTML element.
  4315. *
  4316. * @public
  4317. * @memberof PopupElement
  4318. * @returns {HTMLSectionElement}
  4319. */
  4320. render: function PopupElement_render() {
  4321. var wrapper = document.createElement('div');
  4322. wrapper.className = 'popupWrapper';
  4323. // For Popup annotations we hide the entire section because it contains
  4324. // only the popup. However, for Text annotations without a separate Popup
  4325. // annotation, we cannot hide the entire container as the image would
  4326. // disappear too. In that special case, hiding the wrapper suffices.
  4327. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  4328. this.hideElement.setAttribute('hidden', true);
  4329. var popup = document.createElement('div');
  4330. popup.className = 'popup';
  4331. var color = this.color;
  4332. if (color) {
  4333. // Enlighten the color.
  4334. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4335. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4336. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4337. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4338. }
  4339. var contents = this._formatContents(this.contents);
  4340. var title = document.createElement('h1');
  4341. title.textContent = this.title;
  4342. // Attach the event listeners to the trigger element.
  4343. this.trigger.addEventListener('click', this._toggle.bind(this));
  4344. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4345. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4346. popup.addEventListener('click', this._hide.bind(this, true));
  4347. popup.appendChild(title);
  4348. popup.appendChild(contents);
  4349. wrapper.appendChild(popup);
  4350. return wrapper;
  4351. },
  4352. /**
  4353. * Format the contents of the popup by adding newlines where necessary.
  4354. *
  4355. * @private
  4356. * @param {string} contents
  4357. * @memberof PopupElement
  4358. * @returns {HTMLParagraphElement}
  4359. */
  4360. _formatContents: function PopupElement_formatContents(contents) {
  4361. var p = document.createElement('p');
  4362. var lines = contents.split(/(?:\r\n?|\n)/);
  4363. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4364. var line = lines[i];
  4365. p.appendChild(document.createTextNode(line));
  4366. if (i < (ii - 1)) {
  4367. p.appendChild(document.createElement('br'));
  4368. }
  4369. }
  4370. return p;
  4371. },
  4372. /**
  4373. * Toggle the visibility of the popup.
  4374. *
  4375. * @private
  4376. * @memberof PopupElement
  4377. */
  4378. _toggle: function PopupElement_toggle() {
  4379. if (this.pinned) {
  4380. this._hide(true);
  4381. } else {
  4382. this._show(true);
  4383. }
  4384. },
  4385. /**
  4386. * Show the popup.
  4387. *
  4388. * @private
  4389. * @param {boolean} pin
  4390. * @memberof PopupElement
  4391. */
  4392. _show: function PopupElement_show(pin) {
  4393. if (pin) {
  4394. this.pinned = true;
  4395. }
  4396. if (this.hideElement.hasAttribute('hidden')) {
  4397. this.hideElement.removeAttribute('hidden');
  4398. this.container.style.zIndex += 1;
  4399. }
  4400. },
  4401. /**
  4402. * Hide the popup.
  4403. *
  4404. * @private
  4405. * @param {boolean} unpin
  4406. * @memberof PopupElement
  4407. */
  4408. _hide: function PopupElement_hide(unpin) {
  4409. if (unpin) {
  4410. this.pinned = false;
  4411. }
  4412. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4413. this.hideElement.setAttribute('hidden', true);
  4414. this.container.style.zIndex -= 1;
  4415. }
  4416. }
  4417. };
  4418. return PopupElement;
  4419. })();
  4420. /**
  4421. * @class
  4422. * @alias HighlightAnnotationElement
  4423. */
  4424. var HighlightAnnotationElement = (
  4425. function HighlightAnnotationElementClosure() {
  4426. function HighlightAnnotationElement(parameters) {
  4427. var isRenderable = !!(parameters.data.hasPopup ||
  4428. parameters.data.title || parameters.data.contents);
  4429. AnnotationElement.call(this, parameters, isRenderable);
  4430. }
  4431. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4432. /**
  4433. * Render the highlight annotation's HTML element in the empty container.
  4434. *
  4435. * @public
  4436. * @memberof HighlightAnnotationElement
  4437. * @returns {HTMLSectionElement}
  4438. */
  4439. render: function HighlightAnnotationElement_render() {
  4440. this.container.className = 'highlightAnnotation';
  4441. if (!this.data.hasPopup) {
  4442. this._createPopup(this.container, null, this.data);
  4443. }
  4444. return this.container;
  4445. }
  4446. });
  4447. return HighlightAnnotationElement;
  4448. })();
  4449. /**
  4450. * @class
  4451. * @alias UnderlineAnnotationElement
  4452. */
  4453. var UnderlineAnnotationElement = (
  4454. function UnderlineAnnotationElementClosure() {
  4455. function UnderlineAnnotationElement(parameters) {
  4456. var isRenderable = !!(parameters.data.hasPopup ||
  4457. parameters.data.title || parameters.data.contents);
  4458. AnnotationElement.call(this, parameters, isRenderable);
  4459. }
  4460. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4461. /**
  4462. * Render the underline annotation's HTML element in the empty container.
  4463. *
  4464. * @public
  4465. * @memberof UnderlineAnnotationElement
  4466. * @returns {HTMLSectionElement}
  4467. */
  4468. render: function UnderlineAnnotationElement_render() {
  4469. this.container.className = 'underlineAnnotation';
  4470. if (!this.data.hasPopup) {
  4471. this._createPopup(this.container, null, this.data);
  4472. }
  4473. return this.container;
  4474. }
  4475. });
  4476. return UnderlineAnnotationElement;
  4477. })();
  4478. /**
  4479. * @class
  4480. * @alias SquigglyAnnotationElement
  4481. */
  4482. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  4483. function SquigglyAnnotationElement(parameters) {
  4484. var isRenderable = !!(parameters.data.hasPopup ||
  4485. parameters.data.title || parameters.data.contents);
  4486. AnnotationElement.call(this, parameters, isRenderable);
  4487. }
  4488. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4489. /**
  4490. * Render the squiggly annotation's HTML element in the empty container.
  4491. *
  4492. * @public
  4493. * @memberof SquigglyAnnotationElement
  4494. * @returns {HTMLSectionElement}
  4495. */
  4496. render: function SquigglyAnnotationElement_render() {
  4497. this.container.className = 'squigglyAnnotation';
  4498. if (!this.data.hasPopup) {
  4499. this._createPopup(this.container, null, this.data);
  4500. }
  4501. return this.container;
  4502. }
  4503. });
  4504. return SquigglyAnnotationElement;
  4505. })();
  4506. /**
  4507. * @class
  4508. * @alias StrikeOutAnnotationElement
  4509. */
  4510. var StrikeOutAnnotationElement = (
  4511. function StrikeOutAnnotationElementClosure() {
  4512. function StrikeOutAnnotationElement(parameters) {
  4513. var isRenderable = !!(parameters.data.hasPopup ||
  4514. parameters.data.title || parameters.data.contents);
  4515. AnnotationElement.call(this, parameters, isRenderable);
  4516. }
  4517. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4518. /**
  4519. * Render the strikeout annotation's HTML element in the empty container.
  4520. *
  4521. * @public
  4522. * @memberof StrikeOutAnnotationElement
  4523. * @returns {HTMLSectionElement}
  4524. */
  4525. render: function StrikeOutAnnotationElement_render() {
  4526. this.container.className = 'strikeoutAnnotation';
  4527. if (!this.data.hasPopup) {
  4528. this._createPopup(this.container, null, this.data);
  4529. }
  4530. return this.container;
  4531. }
  4532. });
  4533. return StrikeOutAnnotationElement;
  4534. })();
  4535. /**
  4536. * @class
  4537. * @alias FileAttachmentAnnotationElement
  4538. */
  4539. var FileAttachmentAnnotationElement = (
  4540. function FileAttachmentAnnotationElementClosure() {
  4541. function FileAttachmentAnnotationElement(parameters) {
  4542. AnnotationElement.call(this, parameters, true);
  4543. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4544. this.content = parameters.data.file.content;
  4545. }
  4546. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4547. /**
  4548. * Render the file attachment annotation's HTML element in the empty
  4549. * container.
  4550. *
  4551. * @public
  4552. * @memberof FileAttachmentAnnotationElement
  4553. * @returns {HTMLSectionElement}
  4554. */
  4555. render: function FileAttachmentAnnotationElement_render() {
  4556. this.container.className = 'fileAttachmentAnnotation';
  4557. var trigger = document.createElement('div');
  4558. trigger.style.height = this.container.style.height;
  4559. trigger.style.width = this.container.style.width;
  4560. trigger.addEventListener('dblclick', this._download.bind(this));
  4561. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4562. this._createPopup(this.container, trigger, this.data);
  4563. }
  4564. this.container.appendChild(trigger);
  4565. return this.container;
  4566. },
  4567. /**
  4568. * Download the file attachment associated with this annotation.
  4569. *
  4570. * @private
  4571. * @memberof FileAttachmentAnnotationElement
  4572. */
  4573. _download: function FileAttachmentAnnotationElement_download() {
  4574. if (!this.downloadManager) {
  4575. warn('Download cannot be started due to unavailable download manager');
  4576. return;
  4577. }
  4578. this.downloadManager.downloadData(this.content, this.filename, '');
  4579. }
  4580. });
  4581. return FileAttachmentAnnotationElement;
  4582. })();
  4583. /**
  4584. * @typedef {Object} AnnotationLayerParameters
  4585. * @property {PageViewport} viewport
  4586. * @property {HTMLDivElement} div
  4587. * @property {Array} annotations
  4588. * @property {PDFPage} page
  4589. * @property {IPDFLinkService} linkService
  4590. * @property {string} imageResourcesPath
  4591. */
  4592. /**
  4593. * @class
  4594. * @alias AnnotationLayer
  4595. */
  4596. var AnnotationLayer = (function AnnotationLayerClosure() {
  4597. return {
  4598. /**
  4599. * Render a new annotation layer with all annotation elements.
  4600. *
  4601. * @public
  4602. * @param {AnnotationLayerParameters} parameters
  4603. * @memberof AnnotationLayer
  4604. */
  4605. render: function AnnotationLayer_render(parameters) {
  4606. var annotationElementFactory = new AnnotationElementFactory();
  4607. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4608. var data = parameters.annotations[i];
  4609. if (!data) {
  4610. continue;
  4611. }
  4612. var properties = {
  4613. data: data,
  4614. layer: parameters.div,
  4615. page: parameters.page,
  4616. viewport: parameters.viewport,
  4617. linkService: parameters.linkService,
  4618. downloadManager: parameters.downloadManager,
  4619. imageResourcesPath: parameters.imageResourcesPath ||
  4620. getDefaultSetting('imageResourcesPath')
  4621. };
  4622. var element = annotationElementFactory.create(properties);
  4623. if (element.isRenderable) {
  4624. parameters.div.appendChild(element.render());
  4625. }
  4626. }
  4627. },
  4628. /**
  4629. * Update the annotation elements on existing annotation layer.
  4630. *
  4631. * @public
  4632. * @param {AnnotationLayerParameters} parameters
  4633. * @memberof AnnotationLayer
  4634. */
  4635. update: function AnnotationLayer_update(parameters) {
  4636. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4637. var data = parameters.annotations[i];
  4638. var element = parameters.div.querySelector(
  4639. '[data-annotation-id="' + data.id + '"]');
  4640. if (element) {
  4641. CustomStyle.setProp('transform', element,
  4642. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4643. }
  4644. }
  4645. parameters.div.removeAttribute('hidden');
  4646. }
  4647. };
  4648. })();
  4649. exports.AnnotationLayer = AnnotationLayer;
  4650. }));
  4651. (function (root, factory) {
  4652. {
  4653. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4654. root.pdfjsDisplayDOMUtils);
  4655. }
  4656. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4657. var Util = sharedUtil.Util;
  4658. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4659. var CustomStyle = displayDOMUtils.CustomStyle;
  4660. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4661. /**
  4662. * Text layer render parameters.
  4663. *
  4664. * @typedef {Object} TextLayerRenderParameters
  4665. * @property {TextContent} textContent - Text content to render (the object is
  4666. * returned by the page's getTextContent() method).
  4667. * @property {HTMLElement} container - HTML element that will contain text runs.
  4668. * @property {PageViewport} viewport - The target viewport to properly
  4669. * layout the text runs.
  4670. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4671. * the text items of the textContent input. This is output and shall be
  4672. * initially be set to empty array.
  4673. * @property {number} timeout - (optional) Delay in milliseconds before
  4674. * rendering of the text runs occurs.
  4675. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4676. * text selection enhancement.
  4677. */
  4678. var renderTextLayer = (function renderTextLayerClosure() {
  4679. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4680. var NonWhitespaceRegexp = /\S/;
  4681. function isAllWhitespace(str) {
  4682. return !NonWhitespaceRegexp.test(str);
  4683. }
  4684. function appendText(task, geom, styles) {
  4685. // Initialize all used properties to keep the caches monomorphic.
  4686. var textDiv = document.createElement('div');
  4687. var textDivProperties = {
  4688. angle: 0,
  4689. canvasWidth: 0,
  4690. isWhitespace: false,
  4691. originalTransform: '',
  4692. paddingBottom: 0,
  4693. paddingLeft: 0,
  4694. paddingRight: 0,
  4695. paddingTop: 0,
  4696. scale: 1,
  4697. };
  4698. task._textDivs.push(textDiv);
  4699. if (isAllWhitespace(geom.str)) {
  4700. textDivProperties.isWhitespace = true;
  4701. task._textDivProperties.set(textDiv, textDivProperties);
  4702. return;
  4703. }
  4704. var tx = Util.transform(task._viewport.transform, geom.transform);
  4705. var angle = Math.atan2(tx[1], tx[0]);
  4706. var style = styles[geom.fontName];
  4707. if (style.vertical) {
  4708. angle += Math.PI / 2;
  4709. }
  4710. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4711. var fontAscent = fontHeight;
  4712. if (style.ascent) {
  4713. fontAscent = style.ascent * fontAscent;
  4714. } else if (style.descent) {
  4715. fontAscent = (1 + style.descent) * fontAscent;
  4716. }
  4717. var left;
  4718. var top;
  4719. if (angle === 0) {
  4720. left = tx[4];
  4721. top = tx[5] - fontAscent;
  4722. } else {
  4723. left = tx[4] + (fontAscent * Math.sin(angle));
  4724. top = tx[5] - (fontAscent * Math.cos(angle));
  4725. }
  4726. textDiv.style.left = left + 'px';
  4727. textDiv.style.top = top + 'px';
  4728. textDiv.style.fontSize = fontHeight + 'px';
  4729. textDiv.style.fontFamily = style.fontFamily;
  4730. textDiv.textContent = geom.str;
  4731. // |fontName| is only used by the Font Inspector. This test will succeed
  4732. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4733. // not worth the effort to do a more accurate test. We only use `dataset`
  4734. // here to make the font name available for the debugger.
  4735. if (getDefaultSetting('pdfBug')) {
  4736. textDiv.dataset.fontName = geom.fontName;
  4737. }
  4738. if (angle !== 0) {
  4739. textDivProperties.angle = angle * (180 / Math.PI);
  4740. }
  4741. // We don't bother scaling single-char text divs, because it has very
  4742. // little effect on text highlighting. This makes scrolling on docs with
  4743. // lots of such divs a lot faster.
  4744. if (geom.str.length > 1) {
  4745. if (style.vertical) {
  4746. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4747. } else {
  4748. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4749. }
  4750. }
  4751. task._textDivProperties.set(textDiv, textDivProperties);
  4752. if (task._enhanceTextSelection) {
  4753. var angleCos = 1, angleSin = 0;
  4754. if (angle !== 0) {
  4755. angleCos = Math.cos(angle);
  4756. angleSin = Math.sin(angle);
  4757. }
  4758. var divWidth = (style.vertical ? geom.height : geom.width) *
  4759. task._viewport.scale;
  4760. var divHeight = fontHeight;
  4761. var m, b;
  4762. if (angle !== 0) {
  4763. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  4764. b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  4765. } else {
  4766. b = [left, top, left + divWidth, top + divHeight];
  4767. }
  4768. task._bounds.push({
  4769. left: b[0],
  4770. top: b[1],
  4771. right: b[2],
  4772. bottom: b[3],
  4773. div: textDiv,
  4774. size: [divWidth, divHeight],
  4775. m: m
  4776. });
  4777. }
  4778. }
  4779. function render(task) {
  4780. if (task._canceled) {
  4781. return;
  4782. }
  4783. var textLayerFrag = task._container;
  4784. var textDivs = task._textDivs;
  4785. var capability = task._capability;
  4786. var textDivsLength = textDivs.length;
  4787. // No point in rendering many divs as it would make the browser
  4788. // unusable even after the divs are rendered.
  4789. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4790. task._renderingDone = true;
  4791. capability.resolve();
  4792. return;
  4793. }
  4794. var canvas = document.createElement('canvas');
  4795. canvas.mozOpaque = true;
  4796. var ctx = canvas.getContext('2d', {alpha: false});
  4797. var lastFontSize;
  4798. var lastFontFamily;
  4799. for (var i = 0; i < textDivsLength; i++) {
  4800. var textDiv = textDivs[i];
  4801. var textDivProperties = task._textDivProperties.get(textDiv);
  4802. if (textDivProperties.isWhitespace) {
  4803. continue;
  4804. }
  4805. var fontSize = textDiv.style.fontSize;
  4806. var fontFamily = textDiv.style.fontFamily;
  4807. // Only build font string and set to context if different from last.
  4808. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4809. ctx.font = fontSize + ' ' + fontFamily;
  4810. lastFontSize = fontSize;
  4811. lastFontFamily = fontFamily;
  4812. }
  4813. var width = ctx.measureText(textDiv.textContent).width;
  4814. textLayerFrag.appendChild(textDiv);
  4815. var transform = '';
  4816. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4817. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4818. transform = 'scaleX(' + textDivProperties.scale + ')';
  4819. }
  4820. if (textDivProperties.angle !== 0) {
  4821. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4822. }
  4823. if (transform !== '') {
  4824. textDivProperties.originalTransform = transform;
  4825. CustomStyle.setProp('transform', textDiv, transform);
  4826. }
  4827. task._textDivProperties.set(textDiv, textDivProperties);
  4828. }
  4829. task._renderingDone = true;
  4830. capability.resolve();
  4831. }
  4832. function expand(task) {
  4833. var bounds = task._bounds;
  4834. var viewport = task._viewport;
  4835. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4836. for (var i = 0; i < expanded.length; i++) {
  4837. var div = bounds[i].div;
  4838. var divProperties = task._textDivProperties.get(div);
  4839. if (divProperties.angle === 0) {
  4840. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4841. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4842. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4843. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4844. task._textDivProperties.set(div, divProperties);
  4845. continue;
  4846. }
  4847. // Box is rotated -- trying to find padding so rotated div will not
  4848. // exceed its expanded bounds.
  4849. var e = expanded[i], b = bounds[i];
  4850. var m = b.m, c = m[0], s = m[1];
  4851. // Finding intersections with expanded box.
  4852. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  4853. var ts = new Float64Array(64);
  4854. points.forEach(function (p, i) {
  4855. var t = Util.applyTransform(p, m);
  4856. ts[i + 0] = c && (e.left - t[0]) / c;
  4857. ts[i + 4] = s && (e.top - t[1]) / s;
  4858. ts[i + 8] = c && (e.right - t[0]) / c;
  4859. ts[i + 12] = s && (e.bottom - t[1]) / s;
  4860. ts[i + 16] = s && (e.left - t[0]) / -s;
  4861. ts[i + 20] = c && (e.top - t[1]) / c;
  4862. ts[i + 24] = s && (e.right - t[0]) / -s;
  4863. ts[i + 28] = c && (e.bottom - t[1]) / c;
  4864. ts[i + 32] = c && (e.left - t[0]) / -c;
  4865. ts[i + 36] = s && (e.top - t[1]) / -s;
  4866. ts[i + 40] = c && (e.right - t[0]) / -c;
  4867. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  4868. ts[i + 48] = s && (e.left - t[0]) / s;
  4869. ts[i + 52] = c && (e.top - t[1]) / -c;
  4870. ts[i + 56] = s && (e.right - t[0]) / s;
  4871. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  4872. });
  4873. var findPositiveMin = function (ts, offset, count) {
  4874. var result = 0;
  4875. for (var i = 0; i < count; i++) {
  4876. var t = ts[offset++];
  4877. if (t > 0) {
  4878. result = result ? Math.min(t, result) : t;
  4879. }
  4880. }
  4881. return result;
  4882. };
  4883. // Not based on math, but to simplify calculations, using cos and sin
  4884. // absolute values to not exceed the box (it can but insignificantly).
  4885. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  4886. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  4887. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  4888. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  4889. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  4890. task._textDivProperties.set(div, divProperties);
  4891. }
  4892. }
  4893. function expandBounds(width, height, boxes) {
  4894. var bounds = boxes.map(function (box, i) {
  4895. return {
  4896. x1: box.left,
  4897. y1: box.top,
  4898. x2: box.right,
  4899. y2: box.bottom,
  4900. index: i,
  4901. x1New: undefined,
  4902. x2New: undefined
  4903. };
  4904. });
  4905. expandBoundsLTR(width, bounds);
  4906. var expanded = new Array(boxes.length);
  4907. bounds.forEach(function (b) {
  4908. var i = b.index;
  4909. expanded[i] = {
  4910. left: b.x1New,
  4911. top: 0,
  4912. right: b.x2New,
  4913. bottom: 0
  4914. };
  4915. });
  4916. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  4917. // array and objects.
  4918. boxes.map(function (box, i) {
  4919. var e = expanded[i], b = bounds[i];
  4920. b.x1 = box.top;
  4921. b.y1 = width - e.right;
  4922. b.x2 = box.bottom;
  4923. b.y2 = width - e.left;
  4924. b.index = i;
  4925. b.x1New = undefined;
  4926. b.x2New = undefined;
  4927. });
  4928. expandBoundsLTR(height, bounds);
  4929. bounds.forEach(function (b) {
  4930. var i = b.index;
  4931. expanded[i].top = b.x1New;
  4932. expanded[i].bottom = b.x2New;
  4933. });
  4934. return expanded;
  4935. }
  4936. function expandBoundsLTR(width, bounds) {
  4937. // Sorting by x1 coordinate and walk by the bounds in the same order.
  4938. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; });
  4939. // First we see on the horizon is a fake boundary.
  4940. var fakeBoundary = {
  4941. x1: -Infinity,
  4942. y1: -Infinity,
  4943. x2: 0,
  4944. y2: Infinity,
  4945. index: -1,
  4946. x1New: 0,
  4947. x2New: 0
  4948. };
  4949. var horizon = [{
  4950. start: -Infinity,
  4951. end: Infinity,
  4952. boundary: fakeBoundary
  4953. }];
  4954. bounds.forEach(function (boundary) {
  4955. // Searching for the affected part of horizon.
  4956. // TODO red-black tree or simple binary search
  4957. var i = 0;
  4958. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  4959. i++;
  4960. }
  4961. var j = horizon.length - 1;
  4962. while(j >= 0 && horizon[j].start >= boundary.y2) {
  4963. j--;
  4964. }
  4965. var horizonPart, affectedBoundary;
  4966. var q, k, maxXNew = -Infinity;
  4967. for (q = i; q <= j; q++) {
  4968. horizonPart = horizon[q];
  4969. affectedBoundary = horizonPart.boundary;
  4970. var xNew;
  4971. if (affectedBoundary.x2 > boundary.x1) {
  4972. // In the middle of the previous element, new x shall be at the
  4973. // boundary start. Extending if further if the affected bondary
  4974. // placed on top of the current one.
  4975. xNew = affectedBoundary.index > boundary.index ?
  4976. affectedBoundary.x1New : boundary.x1;
  4977. } else if (affectedBoundary.x2New === undefined) {
  4978. // We have some space in between, new x in middle will be a fair
  4979. // choice.
  4980. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  4981. } else {
  4982. // Affected boundary has x2new set, using it as new x.
  4983. xNew = affectedBoundary.x2New;
  4984. }
  4985. if (xNew > maxXNew) {
  4986. maxXNew = xNew;
  4987. }
  4988. }
  4989. // Set new x1 for current boundary.
  4990. boundary.x1New = maxXNew;
  4991. // Adjusts new x2 for the affected boundaries.
  4992. for (q = i; q <= j; q++) {
  4993. horizonPart = horizon[q];
  4994. affectedBoundary = horizonPart.boundary;
  4995. if (affectedBoundary.x2New === undefined) {
  4996. // Was not set yet, choosing new x if possible.
  4997. if (affectedBoundary.x2 > boundary.x1) {
  4998. // Current and affected boundaries intersect. If affected boundary
  4999. // is placed on top of the current, shrinking the affected.
  5000. if (affectedBoundary.index > boundary.index) {
  5001. affectedBoundary.x2New = affectedBoundary.x2;
  5002. }
  5003. } else {
  5004. affectedBoundary.x2New = maxXNew;
  5005. }
  5006. } else if (affectedBoundary.x2New > maxXNew) {
  5007. // Affected boundary is touching new x, pushing it back.
  5008. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5009. }
  5010. }
  5011. // Fixing the horizon.
  5012. var changedHorizon = [], lastBoundary = null;
  5013. for (q = i; q <= j; q++) {
  5014. horizonPart = horizon[q];
  5015. affectedBoundary = horizonPart.boundary;
  5016. // Checking which boundary will be visible.
  5017. var useBoundary = affectedBoundary.x2 > boundary.x2 ?
  5018. affectedBoundary : boundary;
  5019. if (lastBoundary === useBoundary) {
  5020. // Merging with previous.
  5021. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5022. } else {
  5023. changedHorizon.push({
  5024. start: horizonPart.start,
  5025. end: horizonPart.end,
  5026. boundary: useBoundary
  5027. });
  5028. lastBoundary = useBoundary;
  5029. }
  5030. }
  5031. if (horizon[i].start < boundary.y1) {
  5032. changedHorizon[0].start = boundary.y1;
  5033. changedHorizon.unshift({
  5034. start: horizon[i].start,
  5035. end: boundary.y1,
  5036. boundary: horizon[i].boundary
  5037. });
  5038. }
  5039. if (boundary.y2 < horizon[j].end) {
  5040. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5041. changedHorizon.push({
  5042. start: boundary.y2,
  5043. end: horizon[j].end,
  5044. boundary: horizon[j].boundary
  5045. });
  5046. }
  5047. // Set x2 new of boundary that is no longer visible (see overlapping case
  5048. // above).
  5049. // TODO more efficient, e.g. via reference counting.
  5050. for (q = i; q <= j; q++) {
  5051. horizonPart = horizon[q];
  5052. affectedBoundary = horizonPart.boundary;
  5053. if (affectedBoundary.x2New !== undefined) {
  5054. continue;
  5055. }
  5056. var used = false;
  5057. for (k = i - 1; !used && k >= 0 &&
  5058. horizon[k].start >= affectedBoundary.y1; k--) {
  5059. used = horizon[k].boundary === affectedBoundary;
  5060. }
  5061. for (k = j + 1; !used && k < horizon.length &&
  5062. horizon[k].end <= affectedBoundary.y2; k++) {
  5063. used = horizon[k].boundary === affectedBoundary;
  5064. }
  5065. for (k = 0; !used && k < changedHorizon.length; k++) {
  5066. used = changedHorizon[k].boundary === affectedBoundary;
  5067. }
  5068. if (!used) {
  5069. affectedBoundary.x2New = maxXNew;
  5070. }
  5071. }
  5072. Array.prototype.splice.apply(horizon,
  5073. [i, j - i + 1].concat(changedHorizon));
  5074. });
  5075. // Set new x2 for all unset boundaries.
  5076. horizon.forEach(function (horizonPart) {
  5077. var affectedBoundary = horizonPart.boundary;
  5078. if (affectedBoundary.x2New === undefined) {
  5079. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5080. }
  5081. });
  5082. }
  5083. /**
  5084. * Text layer rendering task.
  5085. *
  5086. * @param {TextContent} textContent
  5087. * @param {HTMLElement} container
  5088. * @param {PageViewport} viewport
  5089. * @param {Array} textDivs
  5090. * @param {boolean} enhanceTextSelection
  5091. * @private
  5092. */
  5093. function TextLayerRenderTask(textContent, container, viewport, textDivs,
  5094. enhanceTextSelection) {
  5095. this._textContent = textContent;
  5096. this._container = container;
  5097. this._viewport = viewport;
  5098. this._textDivs = textDivs || [];
  5099. this._textDivProperties = new WeakMap();
  5100. this._renderingDone = false;
  5101. this._canceled = false;
  5102. this._capability = createPromiseCapability();
  5103. this._renderTimer = null;
  5104. this._bounds = [];
  5105. this._enhanceTextSelection = !!enhanceTextSelection;
  5106. this._expanded = false;
  5107. }
  5108. TextLayerRenderTask.prototype = {
  5109. get promise() {
  5110. return this._capability.promise;
  5111. },
  5112. cancel: function TextLayer_cancel() {
  5113. this._canceled = true;
  5114. if (this._renderTimer !== null) {
  5115. clearTimeout(this._renderTimer);
  5116. this._renderTimer = null;
  5117. }
  5118. this._capability.reject('canceled');
  5119. },
  5120. _render: function TextLayer_render(timeout) {
  5121. var textItems = this._textContent.items;
  5122. var textStyles = this._textContent.styles;
  5123. for (var i = 0, len = textItems.length; i < len; i++) {
  5124. appendText(this, textItems[i], textStyles);
  5125. }
  5126. if (!timeout) { // Render right away
  5127. render(this);
  5128. } else { // Schedule
  5129. var self = this;
  5130. this._renderTimer = setTimeout(function() {
  5131. render(self);
  5132. self._renderTimer = null;
  5133. }, timeout);
  5134. }
  5135. },
  5136. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5137. if (!this._enhanceTextSelection || !this._renderingDone) {
  5138. return;
  5139. }
  5140. if (!this._expanded) {
  5141. expand(this);
  5142. this._expanded = true;
  5143. this._bounds.length = 0;
  5144. }
  5145. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5146. var div = this._textDivs[i];
  5147. var divProperties = this._textDivProperties.get(div);
  5148. if (expandDivs) {
  5149. var transform = '';
  5150. if (divProperties.scale !== 1) {
  5151. transform = 'scaleX(' + divProperties.scale + ')';
  5152. }
  5153. if (divProperties.angle !== 0) {
  5154. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5155. }
  5156. if (divProperties.paddingLeft !== 0) {
  5157. div.style.paddingLeft =
  5158. (divProperties.paddingLeft / divProperties.scale) + 'px';
  5159. transform += ' translateX(' +
  5160. (-divProperties.paddingLeft / divProperties.scale) + 'px)';
  5161. }
  5162. if (divProperties.paddingTop !== 0) {
  5163. div.style.paddingTop = divProperties.paddingTop + 'px';
  5164. transform += ' translateY(' + (-divProperties.paddingTop) + 'px)';
  5165. }
  5166. if (divProperties.paddingRight !== 0) {
  5167. div.style.paddingRight =
  5168. (divProperties.paddingRight / divProperties.scale) + 'px';
  5169. }
  5170. if (divProperties.paddingBottom !== 0) {
  5171. div.style.paddingBottom = divProperties.paddingBottom + 'px';
  5172. }
  5173. if (transform !== '') {
  5174. CustomStyle.setProp('transform', div, transform);
  5175. }
  5176. } else {
  5177. div.style.padding = 0;
  5178. CustomStyle.setProp('transform', div,
  5179. divProperties.originalTransform);
  5180. }
  5181. }
  5182. },
  5183. };
  5184. /**
  5185. * Starts rendering of the text layer.
  5186. *
  5187. * @param {TextLayerRenderParameters} renderParameters
  5188. * @returns {TextLayerRenderTask}
  5189. */
  5190. function renderTextLayer(renderParameters) {
  5191. var task = new TextLayerRenderTask(renderParameters.textContent,
  5192. renderParameters.container,
  5193. renderParameters.viewport,
  5194. renderParameters.textDivs,
  5195. renderParameters.enhanceTextSelection);
  5196. task._render(renderParameters.timeout);
  5197. return task;
  5198. }
  5199. return renderTextLayer;
  5200. })();
  5201. exports.renderTextLayer = renderTextLayer;
  5202. }));
  5203. (function (root, factory) {
  5204. {
  5205. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil,
  5206. root.pdfjsDisplayDOMUtils);
  5207. }
  5208. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5209. var shadow = sharedUtil.shadow;
  5210. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5211. var WebGLUtils = (function WebGLUtilsClosure() {
  5212. function loadShader(gl, code, shaderType) {
  5213. var shader = gl.createShader(shaderType);
  5214. gl.shaderSource(shader, code);
  5215. gl.compileShader(shader);
  5216. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5217. if (!compiled) {
  5218. var errorMsg = gl.getShaderInfoLog(shader);
  5219. throw new Error('Error during shader compilation: ' + errorMsg);
  5220. }
  5221. return shader;
  5222. }
  5223. function createVertexShader(gl, code) {
  5224. return loadShader(gl, code, gl.VERTEX_SHADER);
  5225. }
  5226. function createFragmentShader(gl, code) {
  5227. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5228. }
  5229. function createProgram(gl, shaders) {
  5230. var program = gl.createProgram();
  5231. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5232. gl.attachShader(program, shaders[i]);
  5233. }
  5234. gl.linkProgram(program);
  5235. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5236. if (!linked) {
  5237. var errorMsg = gl.getProgramInfoLog(program);
  5238. throw new Error('Error during program linking: ' + errorMsg);
  5239. }
  5240. return program;
  5241. }
  5242. function createTexture(gl, image, textureId) {
  5243. gl.activeTexture(textureId);
  5244. var texture = gl.createTexture();
  5245. gl.bindTexture(gl.TEXTURE_2D, texture);
  5246. // Set the parameters so we can render any size image.
  5247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5251. // Upload the image into the texture.
  5252. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5253. return texture;
  5254. }
  5255. var currentGL, currentCanvas;
  5256. function generateGL() {
  5257. if (currentGL) {
  5258. return;
  5259. }
  5260. currentCanvas = document.createElement('canvas');
  5261. currentGL = currentCanvas.getContext('webgl',
  5262. { premultipliedalpha: false });
  5263. }
  5264. var smaskVertexShaderCode = '\
  5265. attribute vec2 a_position; \
  5266. attribute vec2 a_texCoord; \
  5267. \
  5268. uniform vec2 u_resolution; \
  5269. \
  5270. varying vec2 v_texCoord; \
  5271. \
  5272. void main() { \
  5273. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5274. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5275. \
  5276. v_texCoord = a_texCoord; \
  5277. } ';
  5278. var smaskFragmentShaderCode = '\
  5279. precision mediump float; \
  5280. \
  5281. uniform vec4 u_backdrop; \
  5282. uniform int u_subtype; \
  5283. uniform sampler2D u_image; \
  5284. uniform sampler2D u_mask; \
  5285. \
  5286. varying vec2 v_texCoord; \
  5287. \
  5288. void main() { \
  5289. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5290. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5291. if (u_backdrop.a > 0.0) { \
  5292. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5293. u_backdrop.rgb * (1.0 - maskColor.a); \
  5294. } \
  5295. float lum; \
  5296. if (u_subtype == 0) { \
  5297. lum = maskColor.a; \
  5298. } else { \
  5299. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5300. maskColor.b * 0.11; \
  5301. } \
  5302. imageColor.a *= lum; \
  5303. imageColor.rgb *= imageColor.a; \
  5304. gl_FragColor = imageColor; \
  5305. } ';
  5306. var smaskCache = null;
  5307. function initSmaskGL() {
  5308. var canvas, gl;
  5309. generateGL();
  5310. canvas = currentCanvas;
  5311. currentCanvas = null;
  5312. gl = currentGL;
  5313. currentGL = null;
  5314. // setup a GLSL program
  5315. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5316. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5317. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5318. gl.useProgram(program);
  5319. var cache = {};
  5320. cache.gl = gl;
  5321. cache.canvas = canvas;
  5322. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5323. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5324. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5325. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5326. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5327. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5328. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5329. // provide texture coordinates for the rectangle.
  5330. var texCoordBuffer = gl.createBuffer();
  5331. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5332. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5333. 0.0, 0.0,
  5334. 1.0, 0.0,
  5335. 0.0, 1.0,
  5336. 0.0, 1.0,
  5337. 1.0, 0.0,
  5338. 1.0, 1.0]), gl.STATIC_DRAW);
  5339. gl.enableVertexAttribArray(texCoordLocation);
  5340. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5341. gl.uniform1i(texLayerLocation, 0);
  5342. gl.uniform1i(texMaskLocation, 1);
  5343. smaskCache = cache;
  5344. }
  5345. function composeSMask(layer, mask, properties) {
  5346. var width = layer.width, height = layer.height;
  5347. if (!smaskCache) {
  5348. initSmaskGL();
  5349. }
  5350. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5351. canvas.width = width;
  5352. canvas.height = height;
  5353. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5354. gl.uniform2f(cache.resolutionLocation, width, height);
  5355. if (properties.backdrop) {
  5356. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5357. properties.backdrop[1], properties.backdrop[2], 1);
  5358. } else {
  5359. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5360. }
  5361. gl.uniform1i(cache.subtypeLocation,
  5362. properties.subtype === 'Luminosity' ? 1 : 0);
  5363. // Create a textures
  5364. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5365. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5366. // Create a buffer and put a single clipspace rectangle in
  5367. // it (2 triangles)
  5368. var buffer = gl.createBuffer();
  5369. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5370. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5371. 0, 0,
  5372. width, 0,
  5373. 0, height,
  5374. 0, height,
  5375. width, 0,
  5376. width, height]), gl.STATIC_DRAW);
  5377. gl.enableVertexAttribArray(cache.positionLocation);
  5378. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5379. // draw
  5380. gl.clearColor(0, 0, 0, 0);
  5381. gl.enable(gl.BLEND);
  5382. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5383. gl.clear(gl.COLOR_BUFFER_BIT);
  5384. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5385. gl.flush();
  5386. gl.deleteTexture(texture);
  5387. gl.deleteTexture(maskTexture);
  5388. gl.deleteBuffer(buffer);
  5389. return canvas;
  5390. }
  5391. var figuresVertexShaderCode = '\
  5392. attribute vec2 a_position; \
  5393. attribute vec3 a_color; \
  5394. \
  5395. uniform vec2 u_resolution; \
  5396. uniform vec2 u_scale; \
  5397. uniform vec2 u_offset; \
  5398. \
  5399. varying vec4 v_color; \
  5400. \
  5401. void main() { \
  5402. vec2 position = (a_position + u_offset) * u_scale; \
  5403. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5404. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5405. \
  5406. v_color = vec4(a_color / 255.0, 1.0); \
  5407. } ';
  5408. var figuresFragmentShaderCode = '\
  5409. precision mediump float; \
  5410. \
  5411. varying vec4 v_color; \
  5412. \
  5413. void main() { \
  5414. gl_FragColor = v_color; \
  5415. } ';
  5416. var figuresCache = null;
  5417. function initFiguresGL() {
  5418. var canvas, gl;
  5419. generateGL();
  5420. canvas = currentCanvas;
  5421. currentCanvas = null;
  5422. gl = currentGL;
  5423. currentGL = null;
  5424. // setup a GLSL program
  5425. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5426. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5427. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5428. gl.useProgram(program);
  5429. var cache = {};
  5430. cache.gl = gl;
  5431. cache.canvas = canvas;
  5432. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5433. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5434. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5435. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5436. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5437. figuresCache = cache;
  5438. }
  5439. function drawFigures(width, height, backgroundColor, figures, context) {
  5440. if (!figuresCache) {
  5441. initFiguresGL();
  5442. }
  5443. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5444. canvas.width = width;
  5445. canvas.height = height;
  5446. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5447. gl.uniform2f(cache.resolutionLocation, width, height);
  5448. // count triangle points
  5449. var count = 0;
  5450. var i, ii, rows;
  5451. for (i = 0, ii = figures.length; i < ii; i++) {
  5452. switch (figures[i].type) {
  5453. case 'lattice':
  5454. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5455. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5456. break;
  5457. case 'triangles':
  5458. count += figures[i].coords.length;
  5459. break;
  5460. }
  5461. }
  5462. // transfer data
  5463. var coords = new Float32Array(count * 2);
  5464. var colors = new Uint8Array(count * 3);
  5465. var coordsMap = context.coords, colorsMap = context.colors;
  5466. var pIndex = 0, cIndex = 0;
  5467. for (i = 0, ii = figures.length; i < ii; i++) {
  5468. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5469. switch (figure.type) {
  5470. case 'lattice':
  5471. var cols = figure.verticesPerRow;
  5472. rows = (ps.length / cols) | 0;
  5473. for (var row = 1; row < rows; row++) {
  5474. var offset = row * cols + 1;
  5475. for (var col = 1; col < cols; col++, offset++) {
  5476. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5477. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5478. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5479. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5480. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5481. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5482. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5483. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5484. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5485. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5486. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5487. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5488. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5489. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5490. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5491. coords[pIndex + 6] = coords[pIndex + 2];
  5492. coords[pIndex + 7] = coords[pIndex + 3];
  5493. coords[pIndex + 8] = coords[pIndex + 4];
  5494. coords[pIndex + 9] = coords[pIndex + 5];
  5495. coords[pIndex + 10] = coordsMap[ps[offset]];
  5496. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5497. colors[cIndex + 9] = colors[cIndex + 3];
  5498. colors[cIndex + 10] = colors[cIndex + 4];
  5499. colors[cIndex + 11] = colors[cIndex + 5];
  5500. colors[cIndex + 12] = colors[cIndex + 6];
  5501. colors[cIndex + 13] = colors[cIndex + 7];
  5502. colors[cIndex + 14] = colors[cIndex + 8];
  5503. colors[cIndex + 15] = colorsMap[cs[offset]];
  5504. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5505. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5506. pIndex += 12;
  5507. cIndex += 18;
  5508. }
  5509. }
  5510. break;
  5511. case 'triangles':
  5512. for (var j = 0, jj = ps.length; j < jj; j++) {
  5513. coords[pIndex] = coordsMap[ps[j]];
  5514. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5515. colors[cIndex] = colorsMap[cs[j]];
  5516. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5517. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5518. pIndex += 2;
  5519. cIndex += 3;
  5520. }
  5521. break;
  5522. }
  5523. }
  5524. // draw
  5525. if (backgroundColor) {
  5526. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5527. backgroundColor[2] / 255, 1.0);
  5528. } else {
  5529. gl.clearColor(0, 0, 0, 0);
  5530. }
  5531. gl.clear(gl.COLOR_BUFFER_BIT);
  5532. var coordsBuffer = gl.createBuffer();
  5533. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5534. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5535. gl.enableVertexAttribArray(cache.positionLocation);
  5536. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5537. var colorsBuffer = gl.createBuffer();
  5538. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5539. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5540. gl.enableVertexAttribArray(cache.colorLocation);
  5541. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5542. 0, 0);
  5543. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5544. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5545. gl.drawArrays(gl.TRIANGLES, 0, count);
  5546. gl.flush();
  5547. gl.deleteBuffer(coordsBuffer);
  5548. gl.deleteBuffer(colorsBuffer);
  5549. return canvas;
  5550. }
  5551. function cleanup() {
  5552. if (smaskCache && smaskCache.canvas) {
  5553. smaskCache.canvas.width = 0;
  5554. smaskCache.canvas.height = 0;
  5555. }
  5556. if (figuresCache && figuresCache.canvas) {
  5557. figuresCache.canvas.width = 0;
  5558. figuresCache.canvas.height = 0;
  5559. }
  5560. smaskCache = null;
  5561. figuresCache = null;
  5562. }
  5563. return {
  5564. get isEnabled() {
  5565. if (getDefaultSetting('disableWebGL')) {
  5566. return false;
  5567. }
  5568. var enabled = false;
  5569. try {
  5570. generateGL();
  5571. enabled = !!currentGL;
  5572. } catch (e) { }
  5573. return shadow(this, 'isEnabled', enabled);
  5574. },
  5575. composeSMask: composeSMask,
  5576. drawFigures: drawFigures,
  5577. clear: cleanup
  5578. };
  5579. })();
  5580. exports.WebGLUtils = WebGLUtils;
  5581. }));
  5582. (function (root, factory) {
  5583. {
  5584. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5585. root.pdfjsDisplayWebGL);
  5586. }
  5587. }(this, function (exports, sharedUtil, displayWebGL) {
  5588. var Util = sharedUtil.Util;
  5589. var info = sharedUtil.info;
  5590. var isArray = sharedUtil.isArray;
  5591. var error = sharedUtil.error;
  5592. var WebGLUtils = displayWebGL.WebGLUtils;
  5593. var ShadingIRs = {};
  5594. ShadingIRs.RadialAxial = {
  5595. fromIR: function RadialAxial_fromIR(raw) {
  5596. var type = raw[1];
  5597. var colorStops = raw[2];
  5598. var p0 = raw[3];
  5599. var p1 = raw[4];
  5600. var r0 = raw[5];
  5601. var r1 = raw[6];
  5602. return {
  5603. type: 'Pattern',
  5604. getPattern: function RadialAxial_getPattern(ctx) {
  5605. var grad;
  5606. if (type === 'axial') {
  5607. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5608. } else if (type === 'radial') {
  5609. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5610. }
  5611. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5612. var c = colorStops[i];
  5613. grad.addColorStop(c[0], c[1]);
  5614. }
  5615. return grad;
  5616. }
  5617. };
  5618. }
  5619. };
  5620. var createMeshCanvas = (function createMeshCanvasClosure() {
  5621. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5622. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5623. var coords = context.coords, colors = context.colors;
  5624. var bytes = data.data, rowSize = data.width * 4;
  5625. var tmp;
  5626. if (coords[p1 + 1] > coords[p2 + 1]) {
  5627. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5628. }
  5629. if (coords[p2 + 1] > coords[p3 + 1]) {
  5630. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5631. }
  5632. if (coords[p1 + 1] > coords[p2 + 1]) {
  5633. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5634. }
  5635. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5636. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5637. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5638. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5639. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5640. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5641. if (y1 >= y3) {
  5642. return;
  5643. }
  5644. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5645. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5646. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5647. var minY = Math.round(y1), maxY = Math.round(y3);
  5648. var xa, car, cag, cab;
  5649. var xb, cbr, cbg, cbb;
  5650. var k;
  5651. for (var y = minY; y <= maxY; y++) {
  5652. if (y < y2) {
  5653. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5654. xa = x1 - (x1 - x2) * k;
  5655. car = c1r - (c1r - c2r) * k;
  5656. cag = c1g - (c1g - c2g) * k;
  5657. cab = c1b - (c1b - c2b) * k;
  5658. } else {
  5659. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5660. xa = x2 - (x2 - x3) * k;
  5661. car = c2r - (c2r - c3r) * k;
  5662. cag = c2g - (c2g - c3g) * k;
  5663. cab = c2b - (c2b - c3b) * k;
  5664. }
  5665. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5666. xb = x1 - (x1 - x3) * k;
  5667. cbr = c1r - (c1r - c3r) * k;
  5668. cbg = c1g - (c1g - c3g) * k;
  5669. cbb = c1b - (c1b - c3b) * k;
  5670. var x1_ = Math.round(Math.min(xa, xb));
  5671. var x2_ = Math.round(Math.max(xa, xb));
  5672. var j = rowSize * y + x1_ * 4;
  5673. for (var x = x1_; x <= x2_; x++) {
  5674. k = (xa - x) / (xa - xb);
  5675. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5676. bytes[j++] = (car - (car - cbr) * k) | 0;
  5677. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5678. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5679. bytes[j++] = 255;
  5680. }
  5681. }
  5682. }
  5683. function drawFigure(data, figure, context) {
  5684. var ps = figure.coords;
  5685. var cs = figure.colors;
  5686. var i, ii;
  5687. switch (figure.type) {
  5688. case 'lattice':
  5689. var verticesPerRow = figure.verticesPerRow;
  5690. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5691. var cols = verticesPerRow - 1;
  5692. for (i = 0; i < rows; i++) {
  5693. var q = i * verticesPerRow;
  5694. for (var j = 0; j < cols; j++, q++) {
  5695. drawTriangle(data, context,
  5696. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5697. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5698. drawTriangle(data, context,
  5699. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5700. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5701. }
  5702. }
  5703. break;
  5704. case 'triangles':
  5705. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5706. drawTriangle(data, context,
  5707. ps[i], ps[i + 1], ps[i + 2],
  5708. cs[i], cs[i + 1], cs[i + 2]);
  5709. }
  5710. break;
  5711. default:
  5712. error('illigal figure');
  5713. break;
  5714. }
  5715. }
  5716. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5717. backgroundColor, cachedCanvases) {
  5718. // we will increase scale on some weird factor to let antialiasing take
  5719. // care of "rough" edges
  5720. var EXPECTED_SCALE = 1.1;
  5721. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5722. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5723. // We need to keep transparent border around our pattern for fill():
  5724. // createPattern with 'no-repeat' will bleed edges across entire area.
  5725. var BORDER_SIZE = 2;
  5726. var offsetX = Math.floor(bounds[0]);
  5727. var offsetY = Math.floor(bounds[1]);
  5728. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5729. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5730. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5731. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5732. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5733. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5734. var scaleX = boundsWidth / width;
  5735. var scaleY = boundsHeight / height;
  5736. var context = {
  5737. coords: coords,
  5738. colors: colors,
  5739. offsetX: -offsetX,
  5740. offsetY: -offsetY,
  5741. scaleX: 1 / scaleX,
  5742. scaleY: 1 / scaleY
  5743. };
  5744. var paddedWidth = width + BORDER_SIZE * 2;
  5745. var paddedHeight = height + BORDER_SIZE * 2;
  5746. var canvas, tmpCanvas, i, ii;
  5747. if (WebGLUtils.isEnabled) {
  5748. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5749. figures, context);
  5750. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5751. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5752. false);
  5753. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5754. canvas = tmpCanvas.canvas;
  5755. } else {
  5756. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5757. false);
  5758. var tmpCtx = tmpCanvas.context;
  5759. var data = tmpCtx.createImageData(width, height);
  5760. if (backgroundColor) {
  5761. var bytes = data.data;
  5762. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5763. bytes[i] = backgroundColor[0];
  5764. bytes[i + 1] = backgroundColor[1];
  5765. bytes[i + 2] = backgroundColor[2];
  5766. bytes[i + 3] = 255;
  5767. }
  5768. }
  5769. for (i = 0; i < figures.length; i++) {
  5770. drawFigure(data, figures[i], context);
  5771. }
  5772. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5773. canvas = tmpCanvas.canvas;
  5774. }
  5775. return {canvas: canvas,
  5776. offsetX: offsetX - BORDER_SIZE * scaleX,
  5777. offsetY: offsetY - BORDER_SIZE * scaleY,
  5778. scaleX: scaleX, scaleY: scaleY};
  5779. }
  5780. return createMeshCanvas;
  5781. })();
  5782. ShadingIRs.Mesh = {
  5783. fromIR: function Mesh_fromIR(raw) {
  5784. //var type = raw[1];
  5785. var coords = raw[2];
  5786. var colors = raw[3];
  5787. var figures = raw[4];
  5788. var bounds = raw[5];
  5789. var matrix = raw[6];
  5790. //var bbox = raw[7];
  5791. var background = raw[8];
  5792. return {
  5793. type: 'Pattern',
  5794. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5795. var scale;
  5796. if (shadingFill) {
  5797. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5798. } else {
  5799. // Obtain scale from matrix and current transformation matrix.
  5800. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5801. if (matrix) {
  5802. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5803. scale = [scale[0] * matrixScale[0],
  5804. scale[1] * matrixScale[1]];
  5805. }
  5806. }
  5807. // Rasterizing on the main thread since sending/queue large canvases
  5808. // might cause OOM.
  5809. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5810. colors, figures, shadingFill ? null : background,
  5811. owner.cachedCanvases);
  5812. if (!shadingFill) {
  5813. ctx.setTransform.apply(ctx, owner.baseTransform);
  5814. if (matrix) {
  5815. ctx.transform.apply(ctx, matrix);
  5816. }
  5817. }
  5818. ctx.translate(temporaryPatternCanvas.offsetX,
  5819. temporaryPatternCanvas.offsetY);
  5820. ctx.scale(temporaryPatternCanvas.scaleX,
  5821. temporaryPatternCanvas.scaleY);
  5822. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5823. }
  5824. };
  5825. }
  5826. };
  5827. ShadingIRs.Dummy = {
  5828. fromIR: function Dummy_fromIR() {
  5829. return {
  5830. type: 'Pattern',
  5831. getPattern: function Dummy_fromIR_getPattern() {
  5832. return 'hotpink';
  5833. }
  5834. };
  5835. }
  5836. };
  5837. function getShadingPatternFromIR(raw) {
  5838. var shadingIR = ShadingIRs[raw[0]];
  5839. if (!shadingIR) {
  5840. error('Unknown IR type: ' + raw[0]);
  5841. }
  5842. return shadingIR.fromIR(raw);
  5843. }
  5844. var TilingPattern = (function TilingPatternClosure() {
  5845. var PaintType = {
  5846. COLORED: 1,
  5847. UNCOLORED: 2
  5848. };
  5849. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5850. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5851. this.operatorList = IR[2];
  5852. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5853. this.bbox = IR[4];
  5854. this.xstep = IR[5];
  5855. this.ystep = IR[6];
  5856. this.paintType = IR[7];
  5857. this.tilingType = IR[8];
  5858. this.color = color;
  5859. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5860. this.baseTransform = baseTransform;
  5861. this.type = 'Pattern';
  5862. this.ctx = ctx;
  5863. }
  5864. TilingPattern.prototype = {
  5865. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5866. var operatorList = this.operatorList;
  5867. var bbox = this.bbox;
  5868. var xstep = this.xstep;
  5869. var ystep = this.ystep;
  5870. var paintType = this.paintType;
  5871. var tilingType = this.tilingType;
  5872. var color = this.color;
  5873. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5874. info('TilingType: ' + tilingType);
  5875. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5876. var topLeft = [x0, y0];
  5877. // we want the canvas to be as large as the step size
  5878. var botRight = [x0 + xstep, y0 + ystep];
  5879. var width = botRight[0] - topLeft[0];
  5880. var height = botRight[1] - topLeft[1];
  5881. // Obtain scale from matrix and current transformation matrix.
  5882. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5883. var curMatrixScale = Util.singularValueDecompose2dScale(
  5884. this.baseTransform);
  5885. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5886. matrixScale[1] * curMatrixScale[1]];
  5887. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5888. // Use width and height values that are as close as possible to the end
  5889. // result when the pattern is used. Too low value makes the pattern look
  5890. // blurry. Too large value makes it look too crispy.
  5891. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5892. MAX_PATTERN_SIZE);
  5893. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5894. MAX_PATTERN_SIZE);
  5895. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5896. width, height, true);
  5897. var tmpCtx = tmpCanvas.context;
  5898. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5899. graphics.groupLevel = owner.groupLevel;
  5900. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5901. this.setScale(width, height, xstep, ystep);
  5902. this.transformToScale(graphics);
  5903. // transform coordinates to pattern space
  5904. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5905. graphics.transform.apply(graphics, tmpTranslate);
  5906. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5907. graphics.executeOperatorList(operatorList);
  5908. return tmpCanvas.canvas;
  5909. },
  5910. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5911. this.scale = [width / xstep, height / ystep];
  5912. },
  5913. transformToScale: function TilingPattern_transformToScale(graphics) {
  5914. var scale = this.scale;
  5915. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5916. graphics.transform.apply(graphics, tmpScale);
  5917. },
  5918. scaleToContext: function TilingPattern_scaleToContext() {
  5919. var scale = this.scale;
  5920. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5921. },
  5922. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5923. if (bbox && isArray(bbox) && bbox.length === 4) {
  5924. var bboxWidth = x1 - x0;
  5925. var bboxHeight = y1 - y0;
  5926. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5927. graphics.clip();
  5928. graphics.endPath();
  5929. }
  5930. },
  5931. setFillAndStrokeStyleToContext:
  5932. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5933. switch (paintType) {
  5934. case PaintType.COLORED:
  5935. var ctx = this.ctx;
  5936. context.fillStyle = ctx.fillStyle;
  5937. context.strokeStyle = ctx.strokeStyle;
  5938. break;
  5939. case PaintType.UNCOLORED:
  5940. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5941. context.fillStyle = cssColor;
  5942. context.strokeStyle = cssColor;
  5943. break;
  5944. default:
  5945. error('Unsupported paint type: ' + paintType);
  5946. }
  5947. },
  5948. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5949. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5950. ctx = this.ctx;
  5951. ctx.setTransform.apply(ctx, this.baseTransform);
  5952. ctx.transform.apply(ctx, this.matrix);
  5953. this.scaleToContext();
  5954. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5955. }
  5956. };
  5957. return TilingPattern;
  5958. })();
  5959. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  5960. exports.TilingPattern = TilingPattern;
  5961. }));
  5962. (function (root, factory) {
  5963. {
  5964. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  5965. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
  5966. root.pdfjsDisplayWebGL);
  5967. }
  5968. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
  5969. displayWebGL) {
  5970. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  5971. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  5972. var ImageKind = sharedUtil.ImageKind;
  5973. var OPS = sharedUtil.OPS;
  5974. var TextRenderingMode = sharedUtil.TextRenderingMode;
  5975. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  5976. var Util = sharedUtil.Util;
  5977. var assert = sharedUtil.assert;
  5978. var info = sharedUtil.info;
  5979. var isNum = sharedUtil.isNum;
  5980. var isArray = sharedUtil.isArray;
  5981. var isLittleEndian = sharedUtil.isLittleEndian;
  5982. var error = sharedUtil.error;
  5983. var shadow = sharedUtil.shadow;
  5984. var warn = sharedUtil.warn;
  5985. var TilingPattern = displayPatternHelper.TilingPattern;
  5986. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  5987. var WebGLUtils = displayWebGL.WebGLUtils;
  5988. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  5989. // <canvas> contexts store most of the state we need natively.
  5990. // However, PDF needs a bit more state, which we store here.
  5991. // Minimal font size that would be used during canvas fillText operations.
  5992. var MIN_FONT_SIZE = 16;
  5993. // Maximum font size that would be used during canvas fillText operations.
  5994. var MAX_FONT_SIZE = 100;
  5995. var MAX_GROUP_SIZE = 4096;
  5996. // Heuristic value used when enforcing minimum line widths.
  5997. var MIN_WIDTH_FACTOR = 0.65;
  5998. var COMPILE_TYPE3_GLYPHS = true;
  5999. var MAX_SIZE_TO_COMPILE = 1000;
  6000. var FULL_CHUNK_HEIGHT = 16;
  6001. var HasCanvasTypedArraysCached = {
  6002. get value() {
  6003. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6004. }
  6005. };
  6006. var IsLittleEndianCached = {
  6007. get value() {
  6008. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6009. }
  6010. };
  6011. function createScratchCanvas(width, height) {
  6012. var canvas = document.createElement('canvas');
  6013. canvas.width = width;
  6014. canvas.height = height;
  6015. return canvas;
  6016. }
  6017. function addContextCurrentTransform(ctx) {
  6018. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6019. if (!ctx.mozCurrentTransform) {
  6020. ctx._originalSave = ctx.save;
  6021. ctx._originalRestore = ctx.restore;
  6022. ctx._originalRotate = ctx.rotate;
  6023. ctx._originalScale = ctx.scale;
  6024. ctx._originalTranslate = ctx.translate;
  6025. ctx._originalTransform = ctx.transform;
  6026. ctx._originalSetTransform = ctx.setTransform;
  6027. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  6028. ctx._transformStack = [];
  6029. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6030. get: function getCurrentTransform() {
  6031. return this._transformMatrix;
  6032. }
  6033. });
  6034. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6035. get: function getCurrentTransformInverse() {
  6036. // Calculation done using WolframAlpha:
  6037. // http://www.wolframalpha.com/input/?
  6038. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6039. var m = this._transformMatrix;
  6040. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6041. var ad_bc = a * d - b * c;
  6042. var bc_ad = b * c - a * d;
  6043. return [
  6044. d / ad_bc,
  6045. b / bc_ad,
  6046. c / bc_ad,
  6047. a / ad_bc,
  6048. (d * e - c * f) / bc_ad,
  6049. (b * e - a * f) / ad_bc
  6050. ];
  6051. }
  6052. });
  6053. ctx.save = function ctxSave() {
  6054. var old = this._transformMatrix;
  6055. this._transformStack.push(old);
  6056. this._transformMatrix = old.slice(0, 6);
  6057. this._originalSave();
  6058. };
  6059. ctx.restore = function ctxRestore() {
  6060. var prev = this._transformStack.pop();
  6061. if (prev) {
  6062. this._transformMatrix = prev;
  6063. this._originalRestore();
  6064. }
  6065. };
  6066. ctx.translate = function ctxTranslate(x, y) {
  6067. var m = this._transformMatrix;
  6068. m[4] = m[0] * x + m[2] * y + m[4];
  6069. m[5] = m[1] * x + m[3] * y + m[5];
  6070. this._originalTranslate(x, y);
  6071. };
  6072. ctx.scale = function ctxScale(x, y) {
  6073. var m = this._transformMatrix;
  6074. m[0] = m[0] * x;
  6075. m[1] = m[1] * x;
  6076. m[2] = m[2] * y;
  6077. m[3] = m[3] * y;
  6078. this._originalScale(x, y);
  6079. };
  6080. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6081. var m = this._transformMatrix;
  6082. this._transformMatrix = [
  6083. m[0] * a + m[2] * b,
  6084. m[1] * a + m[3] * b,
  6085. m[0] * c + m[2] * d,
  6086. m[1] * c + m[3] * d,
  6087. m[0] * e + m[2] * f + m[4],
  6088. m[1] * e + m[3] * f + m[5]
  6089. ];
  6090. ctx._originalTransform(a, b, c, d, e, f);
  6091. };
  6092. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6093. this._transformMatrix = [a, b, c, d, e, f];
  6094. ctx._originalSetTransform(a, b, c, d, e, f);
  6095. };
  6096. ctx.rotate = function ctxRotate(angle) {
  6097. var cosValue = Math.cos(angle);
  6098. var sinValue = Math.sin(angle);
  6099. var m = this._transformMatrix;
  6100. this._transformMatrix = [
  6101. m[0] * cosValue + m[2] * sinValue,
  6102. m[1] * cosValue + m[3] * sinValue,
  6103. m[0] * (-sinValue) + m[2] * cosValue,
  6104. m[1] * (-sinValue) + m[3] * cosValue,
  6105. m[4],
  6106. m[5]
  6107. ];
  6108. this._originalRotate(angle);
  6109. };
  6110. }
  6111. }
  6112. var CachedCanvases = (function CachedCanvasesClosure() {
  6113. function CachedCanvases() {
  6114. this.cache = Object.create(null);
  6115. }
  6116. CachedCanvases.prototype = {
  6117. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  6118. trackTransform) {
  6119. var canvasEntry;
  6120. if (this.cache[id] !== undefined) {
  6121. canvasEntry = this.cache[id];
  6122. canvasEntry.canvas.width = width;
  6123. canvasEntry.canvas.height = height;
  6124. // reset canvas transform for emulated mozCurrentTransform, if needed
  6125. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6126. } else {
  6127. var canvas = createScratchCanvas(width, height);
  6128. var ctx = canvas.getContext('2d');
  6129. if (trackTransform) {
  6130. addContextCurrentTransform(ctx);
  6131. }
  6132. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  6133. }
  6134. return canvasEntry;
  6135. },
  6136. clear: function () {
  6137. for (var id in this.cache) {
  6138. var canvasEntry = this.cache[id];
  6139. // Zeroing the width and height causes Firefox to release graphics
  6140. // resources immediately, which can greatly reduce memory consumption.
  6141. canvasEntry.canvas.width = 0;
  6142. canvasEntry.canvas.height = 0;
  6143. delete this.cache[id];
  6144. }
  6145. }
  6146. };
  6147. return CachedCanvases;
  6148. })();
  6149. function compileType3Glyph(imgData) {
  6150. var POINT_TO_PROCESS_LIMIT = 1000;
  6151. var width = imgData.width, height = imgData.height;
  6152. var i, j, j0, width1 = width + 1;
  6153. var points = new Uint8Array(width1 * (height + 1));
  6154. var POINT_TYPES =
  6155. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6156. // decodes bit-packed mask data
  6157. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  6158. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6159. for (i = 0, ii = data0.length; i < ii; i++) {
  6160. var mask = 128, elem = data0[i];
  6161. while (mask > 0) {
  6162. data[pos++] = (elem & mask) ? 0 : 255;
  6163. mask >>= 1;
  6164. }
  6165. }
  6166. // finding iteresting points: every point is located between mask pixels,
  6167. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6168. // will have flags assigned based on neighboring mask pixels:
  6169. // 4 | 8
  6170. // --P--
  6171. // 2 | 1
  6172. // We are interested only in points with the flags:
  6173. // - outside corners: 1, 2, 4, 8;
  6174. // - inside corners: 7, 11, 13, 14;
  6175. // - and, intersections: 5, 10.
  6176. var count = 0;
  6177. pos = 0;
  6178. if (data[pos] !== 0) {
  6179. points[0] = 1;
  6180. ++count;
  6181. }
  6182. for (j = 1; j < width; j++) {
  6183. if (data[pos] !== data[pos + 1]) {
  6184. points[j] = data[pos] ? 2 : 1;
  6185. ++count;
  6186. }
  6187. pos++;
  6188. }
  6189. if (data[pos] !== 0) {
  6190. points[j] = 2;
  6191. ++count;
  6192. }
  6193. for (i = 1; i < height; i++) {
  6194. pos = i * lineSize;
  6195. j0 = i * width1;
  6196. if (data[pos - lineSize] !== data[pos]) {
  6197. points[j0] = data[pos] ? 1 : 8;
  6198. ++count;
  6199. }
  6200. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6201. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6202. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6203. for (j = 1; j < width; j++) {
  6204. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  6205. (data[pos - lineSize + 1] ? 8 : 0);
  6206. if (POINT_TYPES[sum]) {
  6207. points[j0 + j] = POINT_TYPES[sum];
  6208. ++count;
  6209. }
  6210. pos++;
  6211. }
  6212. if (data[pos - lineSize] !== data[pos]) {
  6213. points[j0 + j] = data[pos] ? 2 : 4;
  6214. ++count;
  6215. }
  6216. if (count > POINT_TO_PROCESS_LIMIT) {
  6217. return null;
  6218. }
  6219. }
  6220. pos = lineSize * (height - 1);
  6221. j0 = i * width1;
  6222. if (data[pos] !== 0) {
  6223. points[j0] = 8;
  6224. ++count;
  6225. }
  6226. for (j = 1; j < width; j++) {
  6227. if (data[pos] !== data[pos + 1]) {
  6228. points[j0 + j] = data[pos] ? 4 : 8;
  6229. ++count;
  6230. }
  6231. pos++;
  6232. }
  6233. if (data[pos] !== 0) {
  6234. points[j0 + j] = 4;
  6235. ++count;
  6236. }
  6237. if (count > POINT_TO_PROCESS_LIMIT) {
  6238. return null;
  6239. }
  6240. // building outlines
  6241. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6242. var outlines = [];
  6243. for (i = 0; count && i <= height; i++) {
  6244. var p = i * width1;
  6245. var end = p + width;
  6246. while (p < end && !points[p]) {
  6247. p++;
  6248. }
  6249. if (p === end) {
  6250. continue;
  6251. }
  6252. var coords = [p % width1, i];
  6253. var type = points[p], p0 = p, pp;
  6254. do {
  6255. var step = steps[type];
  6256. do {
  6257. p += step;
  6258. } while (!points[p]);
  6259. pp = points[p];
  6260. if (pp !== 5 && pp !== 10) {
  6261. // set new direction
  6262. type = pp;
  6263. // delete mark
  6264. points[p] = 0;
  6265. } else { // type is 5 or 10, ie, a crossing
  6266. // set new direction
  6267. type = pp & ((0x33 * type) >> 4);
  6268. // set new type for "future hit"
  6269. points[p] &= (type >> 2 | type << 2);
  6270. }
  6271. coords.push(p % width1);
  6272. coords.push((p / width1) | 0);
  6273. --count;
  6274. } while (p0 !== p);
  6275. outlines.push(coords);
  6276. --i;
  6277. }
  6278. var drawOutline = function(c) {
  6279. c.save();
  6280. // the path shall be painted in [0..1]x[0..1] space
  6281. c.scale(1 / width, -1 / height);
  6282. c.translate(0, -height);
  6283. c.beginPath();
  6284. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6285. var o = outlines[i];
  6286. c.moveTo(o[0], o[1]);
  6287. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6288. c.lineTo(o[j], o[j+1]);
  6289. }
  6290. }
  6291. c.fill();
  6292. c.beginPath();
  6293. c.restore();
  6294. };
  6295. return drawOutline;
  6296. }
  6297. var CanvasExtraState = (function CanvasExtraStateClosure() {
  6298. function CanvasExtraState(old) {
  6299. // Are soft masks and alpha values shapes or opacities?
  6300. this.alphaIsShape = false;
  6301. this.fontSize = 0;
  6302. this.fontSizeScale = 1;
  6303. this.textMatrix = IDENTITY_MATRIX;
  6304. this.textMatrixScale = 1;
  6305. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6306. this.leading = 0;
  6307. // Current point (in user coordinates)
  6308. this.x = 0;
  6309. this.y = 0;
  6310. // Start of text line (in text coordinates)
  6311. this.lineX = 0;
  6312. this.lineY = 0;
  6313. // Character and word spacing
  6314. this.charSpacing = 0;
  6315. this.wordSpacing = 0;
  6316. this.textHScale = 1;
  6317. this.textRenderingMode = TextRenderingMode.FILL;
  6318. this.textRise = 0;
  6319. // Default fore and background colors
  6320. this.fillColor = '#000000';
  6321. this.strokeColor = '#000000';
  6322. this.patternFill = false;
  6323. // Note: fill alpha applies to all non-stroking operations
  6324. this.fillAlpha = 1;
  6325. this.strokeAlpha = 1;
  6326. this.lineWidth = 1;
  6327. this.activeSMask = null;
  6328. this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
  6329. this.old = old;
  6330. }
  6331. CanvasExtraState.prototype = {
  6332. clone: function CanvasExtraState_clone() {
  6333. return Object.create(this);
  6334. },
  6335. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6336. this.x = x;
  6337. this.y = y;
  6338. }
  6339. };
  6340. return CanvasExtraState;
  6341. })();
  6342. var CanvasGraphics = (function CanvasGraphicsClosure() {
  6343. // Defines the time the executeOperatorList is going to be executing
  6344. // before it stops and shedules a continue of execution.
  6345. var EXECUTION_TIME = 15;
  6346. // Defines the number of steps before checking the execution time
  6347. var EXECUTION_STEPS = 10;
  6348. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6349. this.ctx = canvasCtx;
  6350. this.current = new CanvasExtraState();
  6351. this.stateStack = [];
  6352. this.pendingClip = null;
  6353. this.pendingEOFill = false;
  6354. this.res = null;
  6355. this.xobjs = null;
  6356. this.commonObjs = commonObjs;
  6357. this.objs = objs;
  6358. this.imageLayer = imageLayer;
  6359. this.groupStack = [];
  6360. this.processingType3 = null;
  6361. // Patterns are painted relative to the initial page/form transform, see pdf
  6362. // spec 8.7.2 NOTE 1.
  6363. this.baseTransform = null;
  6364. this.baseTransformStack = [];
  6365. this.groupLevel = 0;
  6366. this.smaskStack = [];
  6367. this.smaskCounter = 0;
  6368. this.tempSMask = null;
  6369. this.cachedCanvases = new CachedCanvases();
  6370. if (canvasCtx) {
  6371. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6372. // the transformation must already be set in canvasCtx._transformMatrix.
  6373. addContextCurrentTransform(canvasCtx);
  6374. }
  6375. this.cachedGetSinglePixelWidth = null;
  6376. }
  6377. function putBinaryImageData(ctx, imgData) {
  6378. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6379. ctx.putImageData(imgData, 0, 0);
  6380. return;
  6381. }
  6382. // Put the image data to the canvas in chunks, rather than putting the
  6383. // whole image at once. This saves JS memory, because the ImageData object
  6384. // is smaller. It also possibly saves C++ memory within the implementation
  6385. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6386. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6387. // because too many putImageData() calls will slow things down.
  6388. //
  6389. // Note: as written, if the last chunk is partial, the putImageData() call
  6390. // will (conceptually) put pixels past the bounds of the canvas. But
  6391. // that's ok; any such pixels are ignored.
  6392. var height = imgData.height, width = imgData.width;
  6393. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6394. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6395. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6396. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6397. var srcPos = 0, destPos;
  6398. var src = imgData.data;
  6399. var dest = chunkImgData.data;
  6400. var i, j, thisChunkHeight, elemsInThisChunk;
  6401. // There are multiple forms in which the pixel data can be passed, and
  6402. // imgData.kind tells us which one this is.
  6403. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6404. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6405. var srcLength = src.byteLength;
  6406. var dest32 = HasCanvasTypedArraysCached.value ?
  6407. new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6408. var dest32DataLength = dest32.length;
  6409. var fullSrcDiff = (width + 7) >> 3;
  6410. var white = 0xFFFFFFFF;
  6411. var black = (IsLittleEndianCached.value ||
  6412. !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
  6413. for (i = 0; i < totalChunks; i++) {
  6414. thisChunkHeight =
  6415. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6416. destPos = 0;
  6417. for (j = 0; j < thisChunkHeight; j++) {
  6418. var srcDiff = srcLength - srcPos;
  6419. var k = 0;
  6420. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  6421. var kEndUnrolled = kEnd & ~7;
  6422. var mask = 0;
  6423. var srcByte = 0;
  6424. for (; k < kEndUnrolled; k += 8) {
  6425. srcByte = src[srcPos++];
  6426. dest32[destPos++] = (srcByte & 128) ? white : black;
  6427. dest32[destPos++] = (srcByte & 64) ? white : black;
  6428. dest32[destPos++] = (srcByte & 32) ? white : black;
  6429. dest32[destPos++] = (srcByte & 16) ? white : black;
  6430. dest32[destPos++] = (srcByte & 8) ? white : black;
  6431. dest32[destPos++] = (srcByte & 4) ? white : black;
  6432. dest32[destPos++] = (srcByte & 2) ? white : black;
  6433. dest32[destPos++] = (srcByte & 1) ? white : black;
  6434. }
  6435. for (; k < kEnd; k++) {
  6436. if (mask === 0) {
  6437. srcByte = src[srcPos++];
  6438. mask = 128;
  6439. }
  6440. dest32[destPos++] = (srcByte & mask) ? white : black;
  6441. mask >>= 1;
  6442. }
  6443. }
  6444. // We ran out of input. Make all remaining pixels transparent.
  6445. while (destPos < dest32DataLength) {
  6446. dest32[destPos++] = 0;
  6447. }
  6448. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6449. }
  6450. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6451. // RGBA, 32-bits per pixel.
  6452. j = 0;
  6453. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6454. for (i = 0; i < fullChunks; i++) {
  6455. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6456. srcPos += elemsInThisChunk;
  6457. ctx.putImageData(chunkImgData, 0, j);
  6458. j += FULL_CHUNK_HEIGHT;
  6459. }
  6460. if (i < totalChunks) {
  6461. elemsInThisChunk = width * partialChunkHeight * 4;
  6462. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6463. ctx.putImageData(chunkImgData, 0, j);
  6464. }
  6465. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6466. // RGB, 24-bits per pixel.
  6467. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6468. elemsInThisChunk = width * thisChunkHeight;
  6469. for (i = 0; i < totalChunks; i++) {
  6470. if (i >= fullChunks) {
  6471. thisChunkHeight = partialChunkHeight;
  6472. elemsInThisChunk = width * thisChunkHeight;
  6473. }
  6474. destPos = 0;
  6475. for (j = elemsInThisChunk; j--;) {
  6476. dest[destPos++] = src[srcPos++];
  6477. dest[destPos++] = src[srcPos++];
  6478. dest[destPos++] = src[srcPos++];
  6479. dest[destPos++] = 255;
  6480. }
  6481. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6482. }
  6483. } else {
  6484. error('bad image kind: ' + imgData.kind);
  6485. }
  6486. }
  6487. function putBinaryImageMask(ctx, imgData) {
  6488. var height = imgData.height, width = imgData.width;
  6489. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6490. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6491. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6492. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6493. var srcPos = 0;
  6494. var src = imgData.data;
  6495. var dest = chunkImgData.data;
  6496. for (var i = 0; i < totalChunks; i++) {
  6497. var thisChunkHeight =
  6498. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6499. // Expand the mask so it can be used by the canvas. Any required
  6500. // inversion has already been handled.
  6501. var destPos = 3; // alpha component offset
  6502. for (var j = 0; j < thisChunkHeight; j++) {
  6503. var mask = 0;
  6504. for (var k = 0; k < width; k++) {
  6505. if (!mask) {
  6506. var elem = src[srcPos++];
  6507. mask = 128;
  6508. }
  6509. dest[destPos] = (elem & mask) ? 0 : 255;
  6510. destPos += 4;
  6511. mask >>= 1;
  6512. }
  6513. }
  6514. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6515. }
  6516. }
  6517. function copyCtxState(sourceCtx, destCtx) {
  6518. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6519. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6520. 'globalCompositeOperation', 'font'];
  6521. for (var i = 0, ii = properties.length; i < ii; i++) {
  6522. var property = properties[i];
  6523. if (sourceCtx[property] !== undefined) {
  6524. destCtx[property] = sourceCtx[property];
  6525. }
  6526. }
  6527. if (sourceCtx.setLineDash !== undefined) {
  6528. destCtx.setLineDash(sourceCtx.getLineDash());
  6529. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6530. } else if (sourceCtx.mozDashOffset !== undefined) {
  6531. destCtx.mozDash = sourceCtx.mozDash;
  6532. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  6533. }
  6534. }
  6535. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6536. var length = bytes.length;
  6537. for (var i = 3; i < length; i += 4) {
  6538. var alpha = bytes[i];
  6539. if (alpha === 0) {
  6540. bytes[i - 3] = r0;
  6541. bytes[i - 2] = g0;
  6542. bytes[i - 1] = b0;
  6543. } else if (alpha < 255) {
  6544. var alpha_ = 255 - alpha;
  6545. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6546. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6547. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6548. }
  6549. }
  6550. }
  6551. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6552. var length = maskData.length;
  6553. var scale = 1 / 255;
  6554. for (var i = 3; i < length; i += 4) {
  6555. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6556. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6557. }
  6558. }
  6559. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6560. var length = maskData.length;
  6561. for (var i = 3; i < length; i += 4) {
  6562. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6563. (maskData[i - 2] * 152) + // * 0.59 ....
  6564. (maskData[i - 1] * 28); // * 0.11 ....
  6565. layerData[i] = transferMap ?
  6566. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6567. (layerData[i] * y) >> 16;
  6568. }
  6569. }
  6570. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6571. subtype, backdrop, transferMap) {
  6572. var hasBackdrop = !!backdrop;
  6573. var r0 = hasBackdrop ? backdrop[0] : 0;
  6574. var g0 = hasBackdrop ? backdrop[1] : 0;
  6575. var b0 = hasBackdrop ? backdrop[2] : 0;
  6576. var composeFn;
  6577. if (subtype === 'Luminosity') {
  6578. composeFn = composeSMaskLuminosity;
  6579. } else {
  6580. composeFn = composeSMaskAlpha;
  6581. }
  6582. // processing image in chunks to save memory
  6583. var PIXELS_TO_PROCESS = 1048576;
  6584. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6585. for (var row = 0; row < height; row += chunkSize) {
  6586. var chunkHeight = Math.min(chunkSize, height - row);
  6587. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6588. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6589. if (hasBackdrop) {
  6590. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6591. }
  6592. composeFn(maskData.data, layerData.data, transferMap);
  6593. maskCtx.putImageData(layerData, 0, row);
  6594. }
  6595. }
  6596. function composeSMask(ctx, smask, layerCtx) {
  6597. var mask = smask.canvas;
  6598. var maskCtx = smask.context;
  6599. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6600. smask.offsetX, smask.offsetY);
  6601. var backdrop = smask.backdrop || null;
  6602. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6603. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6604. {subtype: smask.subtype, backdrop: backdrop});
  6605. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6606. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6607. return;
  6608. }
  6609. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6610. smask.subtype, backdrop, smask.transferMap);
  6611. ctx.drawImage(mask, 0, 0);
  6612. }
  6613. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6614. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6615. var NORMAL_CLIP = {};
  6616. var EO_CLIP = {};
  6617. CanvasGraphics.prototype = {
  6618. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6619. transparency) {
  6620. // For pdfs that use blend modes we have to clear the canvas else certain
  6621. // blend modes can look wrong since we'd be blending with a white
  6622. // backdrop. The problem with a transparent backdrop though is we then
  6623. // don't get sub pixel anti aliasing on text, creating temporary
  6624. // transparent canvas when we have blend modes.
  6625. var width = this.ctx.canvas.width;
  6626. var height = this.ctx.canvas.height;
  6627. this.ctx.save();
  6628. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6629. this.ctx.fillRect(0, 0, width, height);
  6630. this.ctx.restore();
  6631. if (transparency) {
  6632. var transparentCanvas = this.cachedCanvases.getCanvas(
  6633. 'transparent', width, height, true);
  6634. this.compositeCtx = this.ctx;
  6635. this.transparentCanvas = transparentCanvas.canvas;
  6636. this.ctx = transparentCanvas.context;
  6637. this.ctx.save();
  6638. // The transform can be applied before rendering, transferring it to
  6639. // the new canvas.
  6640. this.ctx.transform.apply(this.ctx,
  6641. this.compositeCtx.mozCurrentTransform);
  6642. }
  6643. this.ctx.save();
  6644. if (transform) {
  6645. this.ctx.transform.apply(this.ctx, transform);
  6646. }
  6647. this.ctx.transform.apply(this.ctx, viewport.transform);
  6648. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6649. if (this.imageLayer) {
  6650. this.imageLayer.beginLayout();
  6651. }
  6652. },
  6653. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6654. operatorList,
  6655. executionStartIdx, continueCallback,
  6656. stepper) {
  6657. var argsArray = operatorList.argsArray;
  6658. var fnArray = operatorList.fnArray;
  6659. var i = executionStartIdx || 0;
  6660. var argsArrayLen = argsArray.length;
  6661. // Sometimes the OperatorList to execute is empty.
  6662. if (argsArrayLen === i) {
  6663. return i;
  6664. }
  6665. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6666. typeof continueCallback === 'function');
  6667. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6668. var steps = 0;
  6669. var commonObjs = this.commonObjs;
  6670. var objs = this.objs;
  6671. var fnId;
  6672. while (true) {
  6673. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6674. stepper.breakIt(i, continueCallback);
  6675. return i;
  6676. }
  6677. fnId = fnArray[i];
  6678. if (fnId !== OPS.dependency) {
  6679. this[fnId].apply(this, argsArray[i]);
  6680. } else {
  6681. var deps = argsArray[i];
  6682. for (var n = 0, nn = deps.length; n < nn; n++) {
  6683. var depObjId = deps[n];
  6684. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6685. var objsPool = common ? commonObjs : objs;
  6686. // If the promise isn't resolved yet, add the continueCallback
  6687. // to the promise and bail out.
  6688. if (!objsPool.isResolved(depObjId)) {
  6689. objsPool.get(depObjId, continueCallback);
  6690. return i;
  6691. }
  6692. }
  6693. }
  6694. i++;
  6695. // If the entire operatorList was executed, stop as were done.
  6696. if (i === argsArrayLen) {
  6697. return i;
  6698. }
  6699. // If the execution took longer then a certain amount of time and
  6700. // `continueCallback` is specified, interrupt the execution.
  6701. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6702. if (Date.now() > endTime) {
  6703. continueCallback();
  6704. return i;
  6705. }
  6706. steps = 0;
  6707. }
  6708. // If the operatorList isn't executed completely yet OR the execution
  6709. // time was short enough, do another execution round.
  6710. }
  6711. },
  6712. endDrawing: function CanvasGraphics_endDrawing() {
  6713. // Finishing all opened operations such as SMask group painting.
  6714. if (this.current.activeSMask !== null) {
  6715. this.endSMaskGroup();
  6716. }
  6717. this.ctx.restore();
  6718. if (this.transparentCanvas) {
  6719. this.ctx = this.compositeCtx;
  6720. this.ctx.save();
  6721. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6722. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6723. this.ctx.restore();
  6724. this.transparentCanvas = null;
  6725. }
  6726. this.cachedCanvases.clear();
  6727. WebGLUtils.clear();
  6728. if (this.imageLayer) {
  6729. this.imageLayer.endLayout();
  6730. }
  6731. },
  6732. // Graphics state
  6733. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6734. this.current.lineWidth = width;
  6735. this.ctx.lineWidth = width;
  6736. },
  6737. setLineCap: function CanvasGraphics_setLineCap(style) {
  6738. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6739. },
  6740. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6741. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6742. },
  6743. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6744. this.ctx.miterLimit = limit;
  6745. },
  6746. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6747. var ctx = this.ctx;
  6748. if (ctx.setLineDash !== undefined) {
  6749. ctx.setLineDash(dashArray);
  6750. ctx.lineDashOffset = dashPhase;
  6751. } else {
  6752. ctx.mozDash = dashArray;
  6753. ctx.mozDashOffset = dashPhase;
  6754. }
  6755. },
  6756. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6757. // Maybe if we one day fully support color spaces this will be important
  6758. // for now we can ignore.
  6759. // TODO set rendering intent?
  6760. },
  6761. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6762. // There's no way to control this with canvas, but we can safely ignore.
  6763. // TODO set flatness?
  6764. },
  6765. setGState: function CanvasGraphics_setGState(states) {
  6766. for (var i = 0, ii = states.length; i < ii; i++) {
  6767. var state = states[i];
  6768. var key = state[0];
  6769. var value = state[1];
  6770. switch (key) {
  6771. case 'LW':
  6772. this.setLineWidth(value);
  6773. break;
  6774. case 'LC':
  6775. this.setLineCap(value);
  6776. break;
  6777. case 'LJ':
  6778. this.setLineJoin(value);
  6779. break;
  6780. case 'ML':
  6781. this.setMiterLimit(value);
  6782. break;
  6783. case 'D':
  6784. this.setDash(value[0], value[1]);
  6785. break;
  6786. case 'RI':
  6787. this.setRenderingIntent(value);
  6788. break;
  6789. case 'FL':
  6790. this.setFlatness(value);
  6791. break;
  6792. case 'Font':
  6793. this.setFont(value[0], value[1]);
  6794. break;
  6795. case 'CA':
  6796. this.current.strokeAlpha = state[1];
  6797. break;
  6798. case 'ca':
  6799. this.current.fillAlpha = state[1];
  6800. this.ctx.globalAlpha = state[1];
  6801. break;
  6802. case 'BM':
  6803. if (value && value.name && (value.name !== 'Normal')) {
  6804. var mode = value.name.replace(/([A-Z])/g,
  6805. function(c) {
  6806. return '-' + c.toLowerCase();
  6807. }
  6808. ).substring(1);
  6809. this.ctx.globalCompositeOperation = mode;
  6810. if (this.ctx.globalCompositeOperation !== mode) {
  6811. warn('globalCompositeOperation "' + mode +
  6812. '" is not supported');
  6813. }
  6814. } else {
  6815. this.ctx.globalCompositeOperation = 'source-over';
  6816. }
  6817. break;
  6818. case 'SMask':
  6819. if (this.current.activeSMask) {
  6820. // If SMask is currrenly used, it needs to be suspended or
  6821. // finished. Suspend only makes sense when at least one save()
  6822. // was performed and state needs to be reverted on restore().
  6823. if (this.stateStack.length > 0 &&
  6824. (this.stateStack[this.stateStack.length - 1].activeSMask ===
  6825. this.current.activeSMask)) {
  6826. this.suspendSMaskGroup();
  6827. } else {
  6828. this.endSMaskGroup();
  6829. }
  6830. }
  6831. this.current.activeSMask = value ? this.tempSMask : null;
  6832. if (this.current.activeSMask) {
  6833. this.beginSMaskGroup();
  6834. }
  6835. this.tempSMask = null;
  6836. break;
  6837. }
  6838. }
  6839. },
  6840. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6841. var activeSMask = this.current.activeSMask;
  6842. var drawnWidth = activeSMask.canvas.width;
  6843. var drawnHeight = activeSMask.canvas.height;
  6844. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6845. var scratchCanvas = this.cachedCanvases.getCanvas(
  6846. cacheId, drawnWidth, drawnHeight, true);
  6847. var currentCtx = this.ctx;
  6848. var currentTransform = currentCtx.mozCurrentTransform;
  6849. this.ctx.save();
  6850. var groupCtx = scratchCanvas.context;
  6851. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6852. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6853. groupCtx.transform.apply(groupCtx, currentTransform);
  6854. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6855. copyCtxState(currentCtx, groupCtx);
  6856. this.ctx = groupCtx;
  6857. this.setGState([
  6858. ['BM', 'Normal'],
  6859. ['ca', 1],
  6860. ['CA', 1]
  6861. ]);
  6862. this.groupStack.push(currentCtx);
  6863. this.groupLevel++;
  6864. },
  6865. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6866. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  6867. // and future ctx state restored.
  6868. var groupCtx = this.ctx;
  6869. this.groupLevel--;
  6870. this.ctx = this.groupStack.pop();
  6871. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6872. this.ctx.restore();
  6873. this.ctx.save(); // save is needed since SMask will be resumed.
  6874. copyCtxState(groupCtx, this.ctx);
  6875. // Saving state for resuming.
  6876. this.current.resumeSMaskCtx = groupCtx;
  6877. // Transform was changed in the SMask canvas, reflecting this change on
  6878. // this.ctx.
  6879. var deltaTransform = Util.transform(
  6880. this.current.activeSMask.startTransformInverse,
  6881. groupCtx.mozCurrentTransform);
  6882. this.ctx.transform.apply(this.ctx, deltaTransform);
  6883. // SMask was composed, the results at the groupCtx can be cleared.
  6884. groupCtx.save();
  6885. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  6886. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  6887. groupCtx.restore();
  6888. },
  6889. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6890. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  6891. // any groupCtx state since restore() command (the only caller) will do
  6892. // that for us. See also beginSMaskGroup.
  6893. var groupCtx = this.current.resumeSMaskCtx;
  6894. var currentCtx = this.ctx;
  6895. this.ctx = groupCtx;
  6896. this.groupStack.push(currentCtx);
  6897. this.groupLevel++;
  6898. },
  6899. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6900. var groupCtx = this.ctx;
  6901. this.groupLevel--;
  6902. this.ctx = this.groupStack.pop();
  6903. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6904. this.ctx.restore();
  6905. copyCtxState(groupCtx, this.ctx);
  6906. // Transform was changed in the SMask canvas, reflecting this change on
  6907. // this.ctx.
  6908. var deltaTransform = Util.transform(
  6909. this.current.activeSMask.startTransformInverse,
  6910. groupCtx.mozCurrentTransform);
  6911. this.ctx.transform.apply(this.ctx, deltaTransform);
  6912. },
  6913. save: function CanvasGraphics_save() {
  6914. this.ctx.save();
  6915. var old = this.current;
  6916. this.stateStack.push(old);
  6917. this.current = old.clone();
  6918. this.current.resumeSMaskCtx = null;
  6919. },
  6920. restore: function CanvasGraphics_restore() {
  6921. // SMask was suspended, we just need to resume it.
  6922. if (this.current.resumeSMaskCtx) {
  6923. this.resumeSMaskGroup();
  6924. }
  6925. // SMask has to be finished once there is no states that are using the
  6926. // same SMask.
  6927. if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
  6928. this.stateStack[this.stateStack.length - 1].activeSMask !==
  6929. this.current.activeSMask)) {
  6930. this.endSMaskGroup();
  6931. }
  6932. if (this.stateStack.length !== 0) {
  6933. this.current = this.stateStack.pop();
  6934. this.ctx.restore();
  6935. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  6936. this.pendingClip = null;
  6937. this.cachedGetSinglePixelWidth = null;
  6938. }
  6939. },
  6940. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  6941. this.ctx.transform(a, b, c, d, e, f);
  6942. this.cachedGetSinglePixelWidth = null;
  6943. },
  6944. // Path
  6945. constructPath: function CanvasGraphics_constructPath(ops, args) {
  6946. var ctx = this.ctx;
  6947. var current = this.current;
  6948. var x = current.x, y = current.y;
  6949. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6950. switch (ops[i] | 0) {
  6951. case OPS.rectangle:
  6952. x = args[j++];
  6953. y = args[j++];
  6954. var width = args[j++];
  6955. var height = args[j++];
  6956. if (width === 0) {
  6957. width = this.getSinglePixelWidth();
  6958. }
  6959. if (height === 0) {
  6960. height = this.getSinglePixelWidth();
  6961. }
  6962. var xw = x + width;
  6963. var yh = y + height;
  6964. this.ctx.moveTo(x, y);
  6965. this.ctx.lineTo(xw, y);
  6966. this.ctx.lineTo(xw, yh);
  6967. this.ctx.lineTo(x, yh);
  6968. this.ctx.lineTo(x, y);
  6969. this.ctx.closePath();
  6970. break;
  6971. case OPS.moveTo:
  6972. x = args[j++];
  6973. y = args[j++];
  6974. ctx.moveTo(x, y);
  6975. break;
  6976. case OPS.lineTo:
  6977. x = args[j++];
  6978. y = args[j++];
  6979. ctx.lineTo(x, y);
  6980. break;
  6981. case OPS.curveTo:
  6982. x = args[j + 4];
  6983. y = args[j + 5];
  6984. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  6985. x, y);
  6986. j += 6;
  6987. break;
  6988. case OPS.curveTo2:
  6989. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  6990. args[j + 2], args[j + 3]);
  6991. x = args[j + 2];
  6992. y = args[j + 3];
  6993. j += 4;
  6994. break;
  6995. case OPS.curveTo3:
  6996. x = args[j + 2];
  6997. y = args[j + 3];
  6998. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6999. j += 4;
  7000. break;
  7001. case OPS.closePath:
  7002. ctx.closePath();
  7003. break;
  7004. }
  7005. }
  7006. current.setCurrentPoint(x, y);
  7007. },
  7008. closePath: function CanvasGraphics_closePath() {
  7009. this.ctx.closePath();
  7010. },
  7011. stroke: function CanvasGraphics_stroke(consumePath) {
  7012. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7013. var ctx = this.ctx;
  7014. var strokeColor = this.current.strokeColor;
  7015. // Prevent drawing too thin lines by enforcing a minimum line width.
  7016. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  7017. this.current.lineWidth);
  7018. // For stroke we want to temporarily change the global alpha to the
  7019. // stroking alpha.
  7020. ctx.globalAlpha = this.current.strokeAlpha;
  7021. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  7022. strokeColor.type === 'Pattern') {
  7023. // for patterns, we transform to pattern space, calculate
  7024. // the pattern, call stroke, and restore to user space
  7025. ctx.save();
  7026. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7027. ctx.stroke();
  7028. ctx.restore();
  7029. } else {
  7030. ctx.stroke();
  7031. }
  7032. if (consumePath) {
  7033. this.consumePath();
  7034. }
  7035. // Restore the global alpha to the fill alpha
  7036. ctx.globalAlpha = this.current.fillAlpha;
  7037. },
  7038. closeStroke: function CanvasGraphics_closeStroke() {
  7039. this.closePath();
  7040. this.stroke();
  7041. },
  7042. fill: function CanvasGraphics_fill(consumePath) {
  7043. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7044. var ctx = this.ctx;
  7045. var fillColor = this.current.fillColor;
  7046. var isPatternFill = this.current.patternFill;
  7047. var needRestore = false;
  7048. if (isPatternFill) {
  7049. ctx.save();
  7050. if (this.baseTransform) {
  7051. ctx.setTransform.apply(ctx, this.baseTransform);
  7052. }
  7053. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7054. needRestore = true;
  7055. }
  7056. if (this.pendingEOFill) {
  7057. if (ctx.mozFillRule !== undefined) {
  7058. ctx.mozFillRule = 'evenodd';
  7059. ctx.fill();
  7060. ctx.mozFillRule = 'nonzero';
  7061. } else {
  7062. ctx.fill('evenodd');
  7063. }
  7064. this.pendingEOFill = false;
  7065. } else {
  7066. ctx.fill();
  7067. }
  7068. if (needRestore) {
  7069. ctx.restore();
  7070. }
  7071. if (consumePath) {
  7072. this.consumePath();
  7073. }
  7074. },
  7075. eoFill: function CanvasGraphics_eoFill() {
  7076. this.pendingEOFill = true;
  7077. this.fill();
  7078. },
  7079. fillStroke: function CanvasGraphics_fillStroke() {
  7080. this.fill(false);
  7081. this.stroke(false);
  7082. this.consumePath();
  7083. },
  7084. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7085. this.pendingEOFill = true;
  7086. this.fillStroke();
  7087. },
  7088. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7089. this.closePath();
  7090. this.fillStroke();
  7091. },
  7092. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7093. this.pendingEOFill = true;
  7094. this.closePath();
  7095. this.fillStroke();
  7096. },
  7097. endPath: function CanvasGraphics_endPath() {
  7098. this.consumePath();
  7099. },
  7100. // Clipping
  7101. clip: function CanvasGraphics_clip() {
  7102. this.pendingClip = NORMAL_CLIP;
  7103. },
  7104. eoClip: function CanvasGraphics_eoClip() {
  7105. this.pendingClip = EO_CLIP;
  7106. },
  7107. // Text
  7108. beginText: function CanvasGraphics_beginText() {
  7109. this.current.textMatrix = IDENTITY_MATRIX;
  7110. this.current.textMatrixScale = 1;
  7111. this.current.x = this.current.lineX = 0;
  7112. this.current.y = this.current.lineY = 0;
  7113. },
  7114. endText: function CanvasGraphics_endText() {
  7115. var paths = this.pendingTextPaths;
  7116. var ctx = this.ctx;
  7117. if (paths === undefined) {
  7118. ctx.beginPath();
  7119. return;
  7120. }
  7121. ctx.save();
  7122. ctx.beginPath();
  7123. for (var i = 0; i < paths.length; i++) {
  7124. var path = paths[i];
  7125. ctx.setTransform.apply(ctx, path.transform);
  7126. ctx.translate(path.x, path.y);
  7127. path.addToPath(ctx, path.fontSize);
  7128. }
  7129. ctx.restore();
  7130. ctx.clip();
  7131. ctx.beginPath();
  7132. delete this.pendingTextPaths;
  7133. },
  7134. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7135. this.current.charSpacing = spacing;
  7136. },
  7137. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7138. this.current.wordSpacing = spacing;
  7139. },
  7140. setHScale: function CanvasGraphics_setHScale(scale) {
  7141. this.current.textHScale = scale / 100;
  7142. },
  7143. setLeading: function CanvasGraphics_setLeading(leading) {
  7144. this.current.leading = -leading;
  7145. },
  7146. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7147. var fontObj = this.commonObjs.get(fontRefName);
  7148. var current = this.current;
  7149. if (!fontObj) {
  7150. error('Can\'t find font for ' + fontRefName);
  7151. }
  7152. current.fontMatrix = (fontObj.fontMatrix ?
  7153. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7154. // A valid matrix needs all main diagonal elements to be non-zero
  7155. // This also ensures we bypass FF bugzilla bug #719844.
  7156. if (current.fontMatrix[0] === 0 ||
  7157. current.fontMatrix[3] === 0) {
  7158. warn('Invalid font matrix for font ' + fontRefName);
  7159. }
  7160. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7161. // and in some docs this can be negative (inverted x-y axes).
  7162. if (size < 0) {
  7163. size = -size;
  7164. current.fontDirection = -1;
  7165. } else {
  7166. current.fontDirection = 1;
  7167. }
  7168. this.current.font = fontObj;
  7169. this.current.fontSize = size;
  7170. if (fontObj.isType3Font) {
  7171. return; // we don't need ctx.font for Type3 fonts
  7172. }
  7173. var name = fontObj.loadedName || 'sans-serif';
  7174. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  7175. (fontObj.bold ? 'bold' : 'normal');
  7176. var italic = fontObj.italic ? 'italic' : 'normal';
  7177. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7178. // Some font backends cannot handle fonts below certain size.
  7179. // Keeping the font at minimal size and using the fontSizeScale to change
  7180. // the current transformation matrix before the fillText/strokeText.
  7181. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7182. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  7183. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7184. this.current.fontSizeScale = size / browserFontSize;
  7185. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7186. this.ctx.font = rule;
  7187. },
  7188. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7189. this.current.textRenderingMode = mode;
  7190. },
  7191. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7192. this.current.textRise = rise;
  7193. },
  7194. moveText: function CanvasGraphics_moveText(x, y) {
  7195. this.current.x = this.current.lineX += x;
  7196. this.current.y = this.current.lineY += y;
  7197. },
  7198. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7199. this.setLeading(-y);
  7200. this.moveText(x, y);
  7201. },
  7202. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7203. this.current.textMatrix = [a, b, c, d, e, f];
  7204. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7205. this.current.x = this.current.lineX = 0;
  7206. this.current.y = this.current.lineY = 0;
  7207. },
  7208. nextLine: function CanvasGraphics_nextLine() {
  7209. this.moveText(0, this.current.leading);
  7210. },
  7211. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7212. var ctx = this.ctx;
  7213. var current = this.current;
  7214. var font = current.font;
  7215. var textRenderingMode = current.textRenderingMode;
  7216. var fontSize = current.fontSize / current.fontSizeScale;
  7217. var fillStrokeMode = textRenderingMode &
  7218. TextRenderingMode.FILL_STROKE_MASK;
  7219. var isAddToPathSet = !!(textRenderingMode &
  7220. TextRenderingMode.ADD_TO_PATH_FLAG);
  7221. var addToPath;
  7222. if (font.disableFontFace || isAddToPathSet) {
  7223. addToPath = font.getPathGenerator(this.commonObjs, character);
  7224. }
  7225. if (font.disableFontFace) {
  7226. ctx.save();
  7227. ctx.translate(x, y);
  7228. ctx.beginPath();
  7229. addToPath(ctx, fontSize);
  7230. if (fillStrokeMode === TextRenderingMode.FILL ||
  7231. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7232. ctx.fill();
  7233. }
  7234. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7235. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7236. ctx.stroke();
  7237. }
  7238. ctx.restore();
  7239. } else {
  7240. if (fillStrokeMode === TextRenderingMode.FILL ||
  7241. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7242. ctx.fillText(character, x, y);
  7243. }
  7244. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7245. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7246. ctx.strokeText(character, x, y);
  7247. }
  7248. }
  7249. if (isAddToPathSet) {
  7250. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7251. paths.push({
  7252. transform: ctx.mozCurrentTransform,
  7253. x: x,
  7254. y: y,
  7255. fontSize: fontSize,
  7256. addToPath: addToPath
  7257. });
  7258. }
  7259. },
  7260. get isFontSubpixelAAEnabled() {
  7261. // Checks if anti-aliasing is enabled when scaled text is painted.
  7262. // On Windows GDI scaled fonts looks bad.
  7263. var ctx = document.createElement('canvas').getContext('2d');
  7264. ctx.scale(1.5, 1);
  7265. ctx.fillText('I', 0, 10);
  7266. var data = ctx.getImageData(0, 0, 10, 10).data;
  7267. var enabled = false;
  7268. for (var i = 3; i < data.length; i += 4) {
  7269. if (data[i] > 0 && data[i] < 255) {
  7270. enabled = true;
  7271. break;
  7272. }
  7273. }
  7274. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7275. },
  7276. showText: function CanvasGraphics_showText(glyphs) {
  7277. var current = this.current;
  7278. var font = current.font;
  7279. if (font.isType3Font) {
  7280. return this.showType3Text(glyphs);
  7281. }
  7282. var fontSize = current.fontSize;
  7283. if (fontSize === 0) {
  7284. return;
  7285. }
  7286. var ctx = this.ctx;
  7287. var fontSizeScale = current.fontSizeScale;
  7288. var charSpacing = current.charSpacing;
  7289. var wordSpacing = current.wordSpacing;
  7290. var fontDirection = current.fontDirection;
  7291. var textHScale = current.textHScale * fontDirection;
  7292. var glyphsLength = glyphs.length;
  7293. var vertical = font.vertical;
  7294. var spacingDir = vertical ? 1 : -1;
  7295. var defaultVMetrics = font.defaultVMetrics;
  7296. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7297. var simpleFillText =
  7298. current.textRenderingMode === TextRenderingMode.FILL &&
  7299. !font.disableFontFace;
  7300. ctx.save();
  7301. ctx.transform.apply(ctx, current.textMatrix);
  7302. ctx.translate(current.x, current.y + current.textRise);
  7303. if (current.patternFill) {
  7304. // TODO: Some shading patterns are not applied correctly to text,
  7305. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7306. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7307. }
  7308. if (fontDirection > 0) {
  7309. ctx.scale(textHScale, -1);
  7310. } else {
  7311. ctx.scale(textHScale, 1);
  7312. }
  7313. var lineWidth = current.lineWidth;
  7314. var scale = current.textMatrixScale;
  7315. if (scale === 0 || lineWidth === 0) {
  7316. var fillStrokeMode = current.textRenderingMode &
  7317. TextRenderingMode.FILL_STROKE_MASK;
  7318. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7319. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7320. this.cachedGetSinglePixelWidth = null;
  7321. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7322. }
  7323. } else {
  7324. lineWidth /= scale;
  7325. }
  7326. if (fontSizeScale !== 1.0) {
  7327. ctx.scale(fontSizeScale, fontSizeScale);
  7328. lineWidth /= fontSizeScale;
  7329. }
  7330. ctx.lineWidth = lineWidth;
  7331. var x = 0, i;
  7332. for (i = 0; i < glyphsLength; ++i) {
  7333. var glyph = glyphs[i];
  7334. if (isNum(glyph)) {
  7335. x += spacingDir * glyph * fontSize / 1000;
  7336. continue;
  7337. }
  7338. var restoreNeeded = false;
  7339. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7340. var character = glyph.fontChar;
  7341. var accent = glyph.accent;
  7342. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7343. var width = glyph.width;
  7344. if (vertical) {
  7345. var vmetric, vx, vy;
  7346. vmetric = glyph.vmetric || defaultVMetrics;
  7347. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7348. vx = -vx * widthAdvanceScale;
  7349. vy = vmetric[2] * widthAdvanceScale;
  7350. width = vmetric ? -vmetric[0] : width;
  7351. scaledX = vx / fontSizeScale;
  7352. scaledY = (x + vy) / fontSizeScale;
  7353. } else {
  7354. scaledX = x / fontSizeScale;
  7355. scaledY = 0;
  7356. }
  7357. if (font.remeasure && width > 0) {
  7358. // Some standard fonts may not have the exact width: rescale per
  7359. // character if measured width is greater than expected glyph width
  7360. // and subpixel-aa is enabled, otherwise just center the glyph.
  7361. var measuredWidth = ctx.measureText(character).width * 1000 /
  7362. fontSize * fontSizeScale;
  7363. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7364. var characterScaleX = width / measuredWidth;
  7365. restoreNeeded = true;
  7366. ctx.save();
  7367. ctx.scale(characterScaleX, 1);
  7368. scaledX /= characterScaleX;
  7369. } else if (width !== measuredWidth) {
  7370. scaledX += (width - measuredWidth) / 2000 *
  7371. fontSize / fontSizeScale;
  7372. }
  7373. }
  7374. // Only attempt to draw the glyph if it is actually in the embedded font
  7375. // file or if there isn't a font file so the fallback font is shown.
  7376. if (glyph.isInFont || font.missingFile) {
  7377. if (simpleFillText && !accent) {
  7378. // common case
  7379. ctx.fillText(character, scaledX, scaledY);
  7380. } else {
  7381. this.paintChar(character, scaledX, scaledY);
  7382. if (accent) {
  7383. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7384. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7385. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7386. }
  7387. }
  7388. }
  7389. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7390. x += charWidth;
  7391. if (restoreNeeded) {
  7392. ctx.restore();
  7393. }
  7394. }
  7395. if (vertical) {
  7396. current.y -= x * textHScale;
  7397. } else {
  7398. current.x += x * textHScale;
  7399. }
  7400. ctx.restore();
  7401. },
  7402. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7403. // Type3 fonts - each glyph is a "mini-PDF"
  7404. var ctx = this.ctx;
  7405. var current = this.current;
  7406. var font = current.font;
  7407. var fontSize = current.fontSize;
  7408. var fontDirection = current.fontDirection;
  7409. var spacingDir = font.vertical ? 1 : -1;
  7410. var charSpacing = current.charSpacing;
  7411. var wordSpacing = current.wordSpacing;
  7412. var textHScale = current.textHScale * fontDirection;
  7413. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7414. var glyphsLength = glyphs.length;
  7415. var isTextInvisible =
  7416. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7417. var i, glyph, width, spacingLength;
  7418. if (isTextInvisible || fontSize === 0) {
  7419. return;
  7420. }
  7421. this.cachedGetSinglePixelWidth = null;
  7422. ctx.save();
  7423. ctx.transform.apply(ctx, current.textMatrix);
  7424. ctx.translate(current.x, current.y);
  7425. ctx.scale(textHScale, fontDirection);
  7426. for (i = 0; i < glyphsLength; ++i) {
  7427. glyph = glyphs[i];
  7428. if (isNum(glyph)) {
  7429. spacingLength = spacingDir * glyph * fontSize / 1000;
  7430. this.ctx.translate(spacingLength, 0);
  7431. current.x += spacingLength * textHScale;
  7432. continue;
  7433. }
  7434. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7435. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7436. if (!operatorList) {
  7437. warn('Type3 character \"' + glyph.operatorListId +
  7438. '\" is not available');
  7439. continue;
  7440. }
  7441. this.processingType3 = glyph;
  7442. this.save();
  7443. ctx.scale(fontSize, fontSize);
  7444. ctx.transform.apply(ctx, fontMatrix);
  7445. this.executeOperatorList(operatorList);
  7446. this.restore();
  7447. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7448. width = transformed[0] * fontSize + spacing;
  7449. ctx.translate(width, 0);
  7450. current.x += width * textHScale;
  7451. }
  7452. ctx.restore();
  7453. this.processingType3 = null;
  7454. },
  7455. // Type3 fonts
  7456. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7457. // We can safely ignore this since the width should be the same
  7458. // as the width in the Widths array.
  7459. },
  7460. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  7461. yWidth,
  7462. llx,
  7463. lly,
  7464. urx,
  7465. ury) {
  7466. // TODO According to the spec we're also suppose to ignore any operators
  7467. // that set color or include images while processing this type3 font.
  7468. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7469. this.clip();
  7470. this.endPath();
  7471. },
  7472. // Color
  7473. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7474. var pattern;
  7475. if (IR[0] === 'TilingPattern') {
  7476. var color = IR[1];
  7477. var baseTransform = this.baseTransform ||
  7478. this.ctx.mozCurrentTransform.slice();
  7479. var self = this;
  7480. var canvasGraphicsFactory = {
  7481. createCanvasGraphics: function (ctx) {
  7482. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7483. }
  7484. };
  7485. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  7486. baseTransform);
  7487. } else {
  7488. pattern = getShadingPatternFromIR(IR);
  7489. }
  7490. return pattern;
  7491. },
  7492. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  7493. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7494. },
  7495. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  7496. this.current.fillColor = this.getColorN_Pattern(arguments);
  7497. this.current.patternFill = true;
  7498. },
  7499. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7500. var color = Util.makeCssRgb(r, g, b);
  7501. this.ctx.strokeStyle = color;
  7502. this.current.strokeColor = color;
  7503. },
  7504. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7505. var color = Util.makeCssRgb(r, g, b);
  7506. this.ctx.fillStyle = color;
  7507. this.current.fillColor = color;
  7508. this.current.patternFill = false;
  7509. },
  7510. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7511. var ctx = this.ctx;
  7512. this.save();
  7513. var pattern = getShadingPatternFromIR(patternIR);
  7514. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7515. var inv = ctx.mozCurrentTransformInverse;
  7516. if (inv) {
  7517. var canvas = ctx.canvas;
  7518. var width = canvas.width;
  7519. var height = canvas.height;
  7520. var bl = Util.applyTransform([0, 0], inv);
  7521. var br = Util.applyTransform([0, height], inv);
  7522. var ul = Util.applyTransform([width, 0], inv);
  7523. var ur = Util.applyTransform([width, height], inv);
  7524. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7525. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7526. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7527. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7528. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7529. } else {
  7530. // HACK to draw the gradient onto an infinite rectangle.
  7531. // PDF gradients are drawn across the entire image while
  7532. // Canvas only allows gradients to be drawn in a rectangle
  7533. // The following bug should allow us to remove this.
  7534. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7535. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7536. }
  7537. this.restore();
  7538. },
  7539. // Images
  7540. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7541. error('Should not call beginInlineImage');
  7542. },
  7543. beginImageData: function CanvasGraphics_beginImageData() {
  7544. error('Should not call beginImageData');
  7545. },
  7546. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7547. bbox) {
  7548. this.save();
  7549. this.baseTransformStack.push(this.baseTransform);
  7550. if (isArray(matrix) && 6 === matrix.length) {
  7551. this.transform.apply(this, matrix);
  7552. }
  7553. this.baseTransform = this.ctx.mozCurrentTransform;
  7554. if (isArray(bbox) && 4 === bbox.length) {
  7555. var width = bbox[2] - bbox[0];
  7556. var height = bbox[3] - bbox[1];
  7557. this.ctx.rect(bbox[0], bbox[1], width, height);
  7558. this.clip();
  7559. this.endPath();
  7560. }
  7561. },
  7562. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7563. this.restore();
  7564. this.baseTransform = this.baseTransformStack.pop();
  7565. },
  7566. beginGroup: function CanvasGraphics_beginGroup(group) {
  7567. this.save();
  7568. var currentCtx = this.ctx;
  7569. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7570. // group results aren't usually that different and they even have tools
  7571. // that ignore this setting. Notes from Rik on implementing:
  7572. // - When you encounter an transparency group, create a new canvas with
  7573. // the dimensions of the bbox
  7574. // - copy the content from the previous canvas to the new canvas
  7575. // - draw as usual
  7576. // - remove the backdrop alpha:
  7577. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7578. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7579. // backdrop
  7580. // - remove background color:
  7581. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7582. if (!group.isolated) {
  7583. info('TODO: Support non-isolated groups.');
  7584. }
  7585. // TODO knockout - supposedly possible with the clever use of compositing
  7586. // modes.
  7587. if (group.knockout) {
  7588. warn('Knockout groups not supported.');
  7589. }
  7590. var currentTransform = currentCtx.mozCurrentTransform;
  7591. if (group.matrix) {
  7592. currentCtx.transform.apply(currentCtx, group.matrix);
  7593. }
  7594. assert(group.bbox, 'Bounding box is required.');
  7595. // Based on the current transform figure out how big the bounding box
  7596. // will actually be.
  7597. var bounds = Util.getAxialAlignedBoundingBox(
  7598. group.bbox,
  7599. currentCtx.mozCurrentTransform);
  7600. // Clip the bounding box to the current canvas.
  7601. var canvasBounds = [0,
  7602. 0,
  7603. currentCtx.canvas.width,
  7604. currentCtx.canvas.height];
  7605. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7606. // Use ceil in case we're between sizes so we don't create canvas that is
  7607. // too small and make the canvas at least 1x1 pixels.
  7608. var offsetX = Math.floor(bounds[0]);
  7609. var offsetY = Math.floor(bounds[1]);
  7610. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7611. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7612. var scaleX = 1, scaleY = 1;
  7613. if (drawnWidth > MAX_GROUP_SIZE) {
  7614. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7615. drawnWidth = MAX_GROUP_SIZE;
  7616. }
  7617. if (drawnHeight > MAX_GROUP_SIZE) {
  7618. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7619. drawnHeight = MAX_GROUP_SIZE;
  7620. }
  7621. var cacheId = 'groupAt' + this.groupLevel;
  7622. if (group.smask) {
  7623. // Using two cache entries is case if masks are used one after another.
  7624. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7625. }
  7626. var scratchCanvas = this.cachedCanvases.getCanvas(
  7627. cacheId, drawnWidth, drawnHeight, true);
  7628. var groupCtx = scratchCanvas.context;
  7629. // Since we created a new canvas that is just the size of the bounding box
  7630. // we have to translate the group ctx.
  7631. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7632. groupCtx.translate(-offsetX, -offsetY);
  7633. groupCtx.transform.apply(groupCtx, currentTransform);
  7634. if (group.smask) {
  7635. // Saving state and cached mask to be used in setGState.
  7636. this.smaskStack.push({
  7637. canvas: scratchCanvas.canvas,
  7638. context: groupCtx,
  7639. offsetX: offsetX,
  7640. offsetY: offsetY,
  7641. scaleX: scaleX,
  7642. scaleY: scaleY,
  7643. subtype: group.smask.subtype,
  7644. backdrop: group.smask.backdrop,
  7645. transferMap: group.smask.transferMap || null,
  7646. startTransformInverse: null, // used during suspend operation
  7647. });
  7648. } else {
  7649. // Setup the current ctx so when the group is popped we draw it at the
  7650. // right location.
  7651. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7652. currentCtx.translate(offsetX, offsetY);
  7653. currentCtx.scale(scaleX, scaleY);
  7654. }
  7655. // The transparency group inherits all off the current graphics state
  7656. // except the blend mode, soft mask, and alpha constants.
  7657. copyCtxState(currentCtx, groupCtx);
  7658. this.ctx = groupCtx;
  7659. this.setGState([
  7660. ['BM', 'Normal'],
  7661. ['ca', 1],
  7662. ['CA', 1]
  7663. ]);
  7664. this.groupStack.push(currentCtx);
  7665. this.groupLevel++;
  7666. // Reseting mask state, masks will be applied on restore of the group.
  7667. this.current.activeSMask = null;
  7668. },
  7669. endGroup: function CanvasGraphics_endGroup(group) {
  7670. this.groupLevel--;
  7671. var groupCtx = this.ctx;
  7672. this.ctx = this.groupStack.pop();
  7673. // Turn off image smoothing to avoid sub pixel interpolation which can
  7674. // look kind of blurry for some pdfs.
  7675. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7676. this.ctx.imageSmoothingEnabled = false;
  7677. } else {
  7678. this.ctx.mozImageSmoothingEnabled = false;
  7679. }
  7680. if (group.smask) {
  7681. this.tempSMask = this.smaskStack.pop();
  7682. } else {
  7683. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7684. }
  7685. this.restore();
  7686. },
  7687. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7688. this.save();
  7689. this.current = new CanvasExtraState();
  7690. if (this.baseTransform) {
  7691. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7692. }
  7693. },
  7694. endAnnotations: function CanvasGraphics_endAnnotations() {
  7695. this.restore();
  7696. },
  7697. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7698. matrix) {
  7699. this.save();
  7700. if (isArray(rect) && 4 === rect.length) {
  7701. var width = rect[2] - rect[0];
  7702. var height = rect[3] - rect[1];
  7703. this.ctx.rect(rect[0], rect[1], width, height);
  7704. this.clip();
  7705. this.endPath();
  7706. }
  7707. this.transform.apply(this, transform);
  7708. this.transform.apply(this, matrix);
  7709. },
  7710. endAnnotation: function CanvasGraphics_endAnnotation() {
  7711. this.restore();
  7712. },
  7713. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7714. var domImage = this.objs.get(objId);
  7715. if (!domImage) {
  7716. warn('Dependent image isn\'t ready yet');
  7717. return;
  7718. }
  7719. this.save();
  7720. var ctx = this.ctx;
  7721. // scale the image to the unit square
  7722. ctx.scale(1 / w, -1 / h);
  7723. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7724. 0, -h, w, h);
  7725. if (this.imageLayer) {
  7726. var currentTransform = ctx.mozCurrentTransformInverse;
  7727. var position = this.getCanvasPosition(0, 0);
  7728. this.imageLayer.appendImage({
  7729. objId: objId,
  7730. left: position[0],
  7731. top: position[1],
  7732. width: w / currentTransform[0],
  7733. height: h / currentTransform[3]
  7734. });
  7735. }
  7736. this.restore();
  7737. },
  7738. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7739. var ctx = this.ctx;
  7740. var width = img.width, height = img.height;
  7741. var fillColor = this.current.fillColor;
  7742. var isPatternFill = this.current.patternFill;
  7743. var glyph = this.processingType3;
  7744. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7745. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7746. glyph.compiled =
  7747. compileType3Glyph({data: img.data, width: width, height: height});
  7748. } else {
  7749. glyph.compiled = null;
  7750. }
  7751. }
  7752. if (glyph && glyph.compiled) {
  7753. glyph.compiled(ctx);
  7754. return;
  7755. }
  7756. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7757. width, height);
  7758. var maskCtx = maskCanvas.context;
  7759. maskCtx.save();
  7760. putBinaryImageMask(maskCtx, img);
  7761. maskCtx.globalCompositeOperation = 'source-in';
  7762. maskCtx.fillStyle = isPatternFill ?
  7763. fillColor.getPattern(maskCtx, this) : fillColor;
  7764. maskCtx.fillRect(0, 0, width, height);
  7765. maskCtx.restore();
  7766. this.paintInlineImageXObject(maskCanvas.canvas);
  7767. },
  7768. paintImageMaskXObjectRepeat:
  7769. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7770. scaleY, positions) {
  7771. var width = imgData.width;
  7772. var height = imgData.height;
  7773. var fillColor = this.current.fillColor;
  7774. var isPatternFill = this.current.patternFill;
  7775. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7776. width, height);
  7777. var maskCtx = maskCanvas.context;
  7778. maskCtx.save();
  7779. putBinaryImageMask(maskCtx, imgData);
  7780. maskCtx.globalCompositeOperation = 'source-in';
  7781. maskCtx.fillStyle = isPatternFill ?
  7782. fillColor.getPattern(maskCtx, this) : fillColor;
  7783. maskCtx.fillRect(0, 0, width, height);
  7784. maskCtx.restore();
  7785. var ctx = this.ctx;
  7786. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7787. ctx.save();
  7788. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7789. ctx.scale(1, -1);
  7790. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7791. 0, -1, 1, 1);
  7792. ctx.restore();
  7793. }
  7794. },
  7795. paintImageMaskXObjectGroup:
  7796. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7797. var ctx = this.ctx;
  7798. var fillColor = this.current.fillColor;
  7799. var isPatternFill = this.current.patternFill;
  7800. for (var i = 0, ii = images.length; i < ii; i++) {
  7801. var image = images[i];
  7802. var width = image.width, height = image.height;
  7803. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7804. width, height);
  7805. var maskCtx = maskCanvas.context;
  7806. maskCtx.save();
  7807. putBinaryImageMask(maskCtx, image);
  7808. maskCtx.globalCompositeOperation = 'source-in';
  7809. maskCtx.fillStyle = isPatternFill ?
  7810. fillColor.getPattern(maskCtx, this) : fillColor;
  7811. maskCtx.fillRect(0, 0, width, height);
  7812. maskCtx.restore();
  7813. ctx.save();
  7814. ctx.transform.apply(ctx, image.transform);
  7815. ctx.scale(1, -1);
  7816. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7817. 0, -1, 1, 1);
  7818. ctx.restore();
  7819. }
  7820. },
  7821. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7822. var imgData = this.objs.get(objId);
  7823. if (!imgData) {
  7824. warn('Dependent image isn\'t ready yet');
  7825. return;
  7826. }
  7827. this.paintInlineImageXObject(imgData);
  7828. },
  7829. paintImageXObjectRepeat:
  7830. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7831. positions) {
  7832. var imgData = this.objs.get(objId);
  7833. if (!imgData) {
  7834. warn('Dependent image isn\'t ready yet');
  7835. return;
  7836. }
  7837. var width = imgData.width;
  7838. var height = imgData.height;
  7839. var map = [];
  7840. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7841. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7842. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7843. }
  7844. this.paintInlineImageXObjectGroup(imgData, map);
  7845. },
  7846. paintInlineImageXObject:
  7847. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7848. var width = imgData.width;
  7849. var height = imgData.height;
  7850. var ctx = this.ctx;
  7851. this.save();
  7852. // scale the image to the unit square
  7853. ctx.scale(1 / width, -1 / height);
  7854. var currentTransform = ctx.mozCurrentTransformInverse;
  7855. var a = currentTransform[0], b = currentTransform[1];
  7856. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7857. var c = currentTransform[2], d = currentTransform[3];
  7858. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7859. var imgToPaint, tmpCanvas;
  7860. // instanceof HTMLElement does not work in jsdom node.js module
  7861. if (imgData instanceof HTMLElement || !imgData.data) {
  7862. imgToPaint = imgData;
  7863. } else {
  7864. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  7865. width, height);
  7866. var tmpCtx = tmpCanvas.context;
  7867. putBinaryImageData(tmpCtx, imgData);
  7868. imgToPaint = tmpCanvas.canvas;
  7869. }
  7870. var paintWidth = width, paintHeight = height;
  7871. var tmpCanvasId = 'prescale1';
  7872. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  7873. // pixels during drawImage operation, painting on the temporary canvas(es)
  7874. // that are twice smaller in size
  7875. while ((widthScale > 2 && paintWidth > 1) ||
  7876. (heightScale > 2 && paintHeight > 1)) {
  7877. var newWidth = paintWidth, newHeight = paintHeight;
  7878. if (widthScale > 2 && paintWidth > 1) {
  7879. newWidth = Math.ceil(paintWidth / 2);
  7880. widthScale /= paintWidth / newWidth;
  7881. }
  7882. if (heightScale > 2 && paintHeight > 1) {
  7883. newHeight = Math.ceil(paintHeight / 2);
  7884. heightScale /= paintHeight / newHeight;
  7885. }
  7886. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  7887. newWidth, newHeight);
  7888. tmpCtx = tmpCanvas.context;
  7889. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7890. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7891. 0, 0, newWidth, newHeight);
  7892. imgToPaint = tmpCanvas.canvas;
  7893. paintWidth = newWidth;
  7894. paintHeight = newHeight;
  7895. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7896. }
  7897. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7898. 0, -height, width, height);
  7899. if (this.imageLayer) {
  7900. var position = this.getCanvasPosition(0, -height);
  7901. this.imageLayer.appendImage({
  7902. imgData: imgData,
  7903. left: position[0],
  7904. top: position[1],
  7905. width: width / currentTransform[0],
  7906. height: height / currentTransform[3]
  7907. });
  7908. }
  7909. this.restore();
  7910. },
  7911. paintInlineImageXObjectGroup:
  7912. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  7913. var ctx = this.ctx;
  7914. var w = imgData.width;
  7915. var h = imgData.height;
  7916. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  7917. var tmpCtx = tmpCanvas.context;
  7918. putBinaryImageData(tmpCtx, imgData);
  7919. for (var i = 0, ii = map.length; i < ii; i++) {
  7920. var entry = map[i];
  7921. ctx.save();
  7922. ctx.transform.apply(ctx, entry.transform);
  7923. ctx.scale(1, -1);
  7924. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  7925. 0, -1, 1, 1);
  7926. if (this.imageLayer) {
  7927. var position = this.getCanvasPosition(entry.x, entry.y);
  7928. this.imageLayer.appendImage({
  7929. imgData: imgData,
  7930. left: position[0],
  7931. top: position[1],
  7932. width: w,
  7933. height: h
  7934. });
  7935. }
  7936. ctx.restore();
  7937. }
  7938. },
  7939. paintSolidColorImageMask:
  7940. function CanvasGraphics_paintSolidColorImageMask() {
  7941. this.ctx.fillRect(0, 0, 1, 1);
  7942. },
  7943. paintXObject: function CanvasGraphics_paintXObject() {
  7944. warn('Unsupported \'paintXObject\' command.');
  7945. },
  7946. // Marked content
  7947. markPoint: function CanvasGraphics_markPoint(tag) {
  7948. // TODO Marked content.
  7949. },
  7950. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  7951. // TODO Marked content.
  7952. },
  7953. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  7954. // TODO Marked content.
  7955. },
  7956. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  7957. tag, properties) {
  7958. // TODO Marked content.
  7959. },
  7960. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  7961. // TODO Marked content.
  7962. },
  7963. // Compatibility
  7964. beginCompat: function CanvasGraphics_beginCompat() {
  7965. // TODO ignore undefined operators (should we do that anyway?)
  7966. },
  7967. endCompat: function CanvasGraphics_endCompat() {
  7968. // TODO stop ignoring undefined operators
  7969. },
  7970. // Helper functions
  7971. consumePath: function CanvasGraphics_consumePath() {
  7972. var ctx = this.ctx;
  7973. if (this.pendingClip) {
  7974. if (this.pendingClip === EO_CLIP) {
  7975. if (ctx.mozFillRule !== undefined) {
  7976. ctx.mozFillRule = 'evenodd';
  7977. ctx.clip();
  7978. ctx.mozFillRule = 'nonzero';
  7979. } else {
  7980. ctx.clip('evenodd');
  7981. }
  7982. } else {
  7983. ctx.clip();
  7984. }
  7985. this.pendingClip = null;
  7986. }
  7987. ctx.beginPath();
  7988. },
  7989. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  7990. if (this.cachedGetSinglePixelWidth === null) {
  7991. // NOTE: The `save` and `restore` commands used below is a workaround
  7992. // that is necessary in order to prevent `mozCurrentTransformInverse`
  7993. // from intermittently returning incorrect values in Firefox, see:
  7994. // https://github.com/mozilla/pdf.js/issues/7188.
  7995. this.ctx.save();
  7996. var inverse = this.ctx.mozCurrentTransformInverse;
  7997. this.ctx.restore();
  7998. // max of the current horizontal and vertical scale
  7999. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  8000. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  8001. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  8002. }
  8003. return this.cachedGetSinglePixelWidth;
  8004. },
  8005. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8006. var transform = this.ctx.mozCurrentTransform;
  8007. return [
  8008. transform[0] * x + transform[2] * y + transform[4],
  8009. transform[1] * x + transform[3] * y + transform[5]
  8010. ];
  8011. }
  8012. };
  8013. for (var op in OPS) {
  8014. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8015. }
  8016. return CanvasGraphics;
  8017. })();
  8018. exports.CanvasGraphics = CanvasGraphics;
  8019. exports.createScratchCanvas = createScratchCanvas;
  8020. }));
  8021. (function (root, factory) {
  8022. {
  8023. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  8024. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  8025. root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8026. }
  8027. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  8028. displayMetadata, displayDOMUtils, amdRequire) {
  8029. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8030. var MessageHandler = sharedUtil.MessageHandler;
  8031. var MissingPDFException = sharedUtil.MissingPDFException;
  8032. var PageViewport = sharedUtil.PageViewport;
  8033. var PasswordResponses = sharedUtil.PasswordResponses;
  8034. var PasswordException = sharedUtil.PasswordException;
  8035. var StatTimer = sharedUtil.StatTimer;
  8036. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8037. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8038. var Util = sharedUtil.Util;
  8039. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8040. var error = sharedUtil.error;
  8041. var deprecated = sharedUtil.deprecated;
  8042. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8043. var info = sharedUtil.info;
  8044. var isInt = sharedUtil.isInt;
  8045. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8046. var isSameOrigin = sharedUtil.isSameOrigin;
  8047. var loadJpegStream = sharedUtil.loadJpegStream;
  8048. var stringToBytes = sharedUtil.stringToBytes;
  8049. var globalScope = sharedUtil.globalScope;
  8050. var warn = sharedUtil.warn;
  8051. var FontFaceObject = displayFontLoader.FontFaceObject;
  8052. var FontLoader = displayFontLoader.FontLoader;
  8053. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8054. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8055. var Metadata = displayMetadata.Metadata;
  8056. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8057. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  8058. var isWorkerDisabled = false;
  8059. var workerSrc;
  8060. var isPostMessageTransfersDisabled = false;
  8061. var useRequireEnsure = false;
  8062. if (typeof window === 'undefined') {
  8063. // node.js - disable worker and set require.ensure.
  8064. isWorkerDisabled = true;
  8065. if (typeof require.ensure === 'undefined') {
  8066. require.ensure = require('node-ensure');
  8067. }
  8068. useRequireEnsure = true;
  8069. }
  8070. if (typeof __webpack_require__ !== 'undefined') {
  8071. useRequireEnsure = true;
  8072. }
  8073. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8074. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8075. }
  8076. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8077. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  8078. require.ensure([], function () {
  8079. var worker = require('./pdf.worker.js');
  8080. callback(worker.WorkerMessageHandler);
  8081. });
  8082. }) : dynamicLoaderSupported ? (function (callback) {
  8083. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8084. callback(worker.WorkerMessageHandler);
  8085. });
  8086. }) : null;
  8087. /**
  8088. * Document initialization / loading parameters object.
  8089. *
  8090. * @typedef {Object} DocumentInitParameters
  8091. * @property {string} url - The URL of the PDF.
  8092. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8093. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8094. * use atob() to convert it to a binary string first.
  8095. * @property {Object} httpHeaders - Basic authentication headers.
  8096. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8097. * Access-Control requests should be made using credentials such as cookies
  8098. * or authorization headers. The default is false.
  8099. * @property {string} password - For decrypting password-protected PDFs.
  8100. * @property {TypedArray} initialData - A typed array with the first portion or
  8101. * all of the pdf data. Used by the extension since some data is already
  8102. * loaded before the switch to range requests.
  8103. * @property {number} length - The PDF file length. It's used for progress
  8104. * reports and range requests operations.
  8105. * @property {PDFDataRangeTransport} range
  8106. * @property {number} rangeChunkSize - Optional parameter to specify
  8107. * maximum number of bytes fetched per range request. The default value is
  8108. * 2^16 = 65536.
  8109. * @property {PDFWorker} worker - The worker that will be used for the loading
  8110. * and parsing of the PDF data.
  8111. */
  8112. /**
  8113. * @typedef {Object} PDFDocumentStats
  8114. * @property {Array} streamTypes - Used stream types in the document (an item
  8115. * is set to true if specific stream ID was used in the document).
  8116. * @property {Array} fontTypes - Used font type in the document (an item is set
  8117. * to true if specific font ID was used in the document).
  8118. */
  8119. /**
  8120. * This is the main entry point for loading a PDF and interacting with it.
  8121. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8122. * is used, which means it must follow the same origin rules that any XHR does
  8123. * e.g. No cross domain requests without CORS.
  8124. *
  8125. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8126. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8127. * already populated with data or parameter object.
  8128. *
  8129. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8130. * if you want to manually serve range requests for data in the PDF.
  8131. *
  8132. * @param {function} passwordCallback (deprecated) It is used to request a
  8133. * password if wrong or no password was provided. The callback receives two
  8134. * parameters: function that needs to be called with new password and reason
  8135. * (see {PasswordResponses}).
  8136. *
  8137. * @param {function} progressCallback (deprecated) It is used to be able to
  8138. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8139. * a loading bar). The callback receives an {Object} with the properties:
  8140. * {number} loaded and {number} total.
  8141. *
  8142. * @return {PDFDocumentLoadingTask}
  8143. */
  8144. function getDocument(src, pdfDataRangeTransport,
  8145. passwordCallback, progressCallback) {
  8146. var task = new PDFDocumentLoadingTask();
  8147. // Support of the obsolete arguments (for compatibility with API v1.0)
  8148. if (arguments.length > 1) {
  8149. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  8150. 'passwordCallback or progressCallback argument');
  8151. }
  8152. if (pdfDataRangeTransport) {
  8153. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8154. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8155. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8156. pdfDataRangeTransport.length = src.length;
  8157. pdfDataRangeTransport.initialData = src.initialData;
  8158. if (!pdfDataRangeTransport.abort) {
  8159. pdfDataRangeTransport.abort = function () {};
  8160. }
  8161. }
  8162. src = Object.create(src);
  8163. src.range = pdfDataRangeTransport;
  8164. }
  8165. task.onPassword = passwordCallback || null;
  8166. task.onProgress = progressCallback || null;
  8167. var source;
  8168. if (typeof src === 'string') {
  8169. source = { url: src };
  8170. } else if (isArrayBuffer(src)) {
  8171. source = { data: src };
  8172. } else if (src instanceof PDFDataRangeTransport) {
  8173. source = { range: src };
  8174. } else {
  8175. if (typeof src !== 'object') {
  8176. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  8177. 'string or a parameter object');
  8178. }
  8179. if (!src.url && !src.data && !src.range) {
  8180. error('Invalid parameter object: need either .data, .range or .url');
  8181. }
  8182. source = src;
  8183. }
  8184. var params = {};
  8185. var rangeTransport = null;
  8186. var worker = null;
  8187. for (var key in source) {
  8188. if (key === 'url' && typeof window !== 'undefined') {
  8189. // The full path is required in the 'url' field.
  8190. params[key] = new URL(source[key], window.location).href;
  8191. continue;
  8192. } else if (key === 'range') {
  8193. rangeTransport = source[key];
  8194. continue;
  8195. } else if (key === 'worker') {
  8196. worker = source[key];
  8197. continue;
  8198. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8199. // Converting string or array-like data to Uint8Array.
  8200. var pdfBytes = source[key];
  8201. if (typeof pdfBytes === 'string') {
  8202. params[key] = stringToBytes(pdfBytes);
  8203. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  8204. !isNaN(pdfBytes.length)) {
  8205. params[key] = new Uint8Array(pdfBytes);
  8206. } else if (isArrayBuffer(pdfBytes)) {
  8207. params[key] = new Uint8Array(pdfBytes);
  8208. } else {
  8209. error('Invalid PDF binary data: either typed array, string or ' +
  8210. 'array-like object is expected in the data property.');
  8211. }
  8212. continue;
  8213. }
  8214. params[key] = source[key];
  8215. }
  8216. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8217. if (!worker) {
  8218. // Worker was not provided -- creating and owning our own.
  8219. worker = new PDFWorker();
  8220. task._worker = worker;
  8221. }
  8222. var docId = task.docId;
  8223. worker.promise.then(function () {
  8224. if (task.destroyed) {
  8225. throw new Error('Loading aborted');
  8226. }
  8227. return _fetchDocument(worker, params, rangeTransport, docId).then(
  8228. function (workerId) {
  8229. if (task.destroyed) {
  8230. throw new Error('Loading aborted');
  8231. }
  8232. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8233. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8234. task._transport = transport;
  8235. messageHandler.send('Ready', null);
  8236. });
  8237. }).catch(task._capability.reject);
  8238. return task;
  8239. }
  8240. /**
  8241. * Starts fetching of specified PDF document/data.
  8242. * @param {PDFWorker} worker
  8243. * @param {Object} source
  8244. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8245. * @param {string} docId Unique document id, used as MessageHandler id.
  8246. * @returns {Promise} The promise, which is resolved when worker id of
  8247. * MessageHandler is known.
  8248. * @private
  8249. */
  8250. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8251. if (worker.destroyed) {
  8252. return Promise.reject(new Error('Worker was destroyed'));
  8253. }
  8254. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8255. source.disableStream = getDefaultSetting('disableStream');
  8256. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8257. if (pdfDataRangeTransport) {
  8258. source.length = pdfDataRangeTransport.length;
  8259. source.initialData = pdfDataRangeTransport.initialData;
  8260. }
  8261. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8262. docId: docId,
  8263. source: source,
  8264. disableRange: getDefaultSetting('disableRange'),
  8265. maxImageSize: getDefaultSetting('maxImageSize'),
  8266. cMapUrl: getDefaultSetting('cMapUrl'),
  8267. cMapPacked: getDefaultSetting('cMapPacked'),
  8268. disableFontFace: getDefaultSetting('disableFontFace'),
  8269. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8270. postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
  8271. !isPostMessageTransfersDisabled,
  8272. }).then(function (workerId) {
  8273. if (worker.destroyed) {
  8274. throw new Error('Worker was destroyed');
  8275. }
  8276. return workerId;
  8277. });
  8278. }
  8279. /**
  8280. * PDF document loading operation.
  8281. * @class
  8282. * @alias PDFDocumentLoadingTask
  8283. */
  8284. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  8285. var nextDocumentId = 0;
  8286. /** @constructs PDFDocumentLoadingTask */
  8287. function PDFDocumentLoadingTask() {
  8288. this._capability = createPromiseCapability();
  8289. this._transport = null;
  8290. this._worker = null;
  8291. /**
  8292. * Unique document loading task id -- used in MessageHandlers.
  8293. * @type {string}
  8294. */
  8295. this.docId = 'd' + (nextDocumentId++);
  8296. /**
  8297. * Shows if loading task is destroyed.
  8298. * @type {boolean}
  8299. */
  8300. this.destroyed = false;
  8301. /**
  8302. * Callback to request a password if wrong or no password was provided.
  8303. * The callback receives two parameters: function that needs to be called
  8304. * with new password and reason (see {PasswordResponses}).
  8305. */
  8306. this.onPassword = null;
  8307. /**
  8308. * Callback to be able to monitor the loading progress of the PDF file
  8309. * (necessary to implement e.g. a loading bar). The callback receives
  8310. * an {Object} with the properties: {number} loaded and {number} total.
  8311. */
  8312. this.onProgress = null;
  8313. /**
  8314. * Callback to when unsupported feature is used. The callback receives
  8315. * an {UNSUPPORTED_FEATURES} argument.
  8316. */
  8317. this.onUnsupportedFeature = null;
  8318. }
  8319. PDFDocumentLoadingTask.prototype =
  8320. /** @lends PDFDocumentLoadingTask.prototype */ {
  8321. /**
  8322. * @return {Promise}
  8323. */
  8324. get promise() {
  8325. return this._capability.promise;
  8326. },
  8327. /**
  8328. * Aborts all network requests and destroys worker.
  8329. * @return {Promise} A promise that is resolved after destruction activity
  8330. * is completed.
  8331. */
  8332. destroy: function () {
  8333. this.destroyed = true;
  8334. var transportDestroyed = !this._transport ? Promise.resolve() :
  8335. this._transport.destroy();
  8336. return transportDestroyed.then(function () {
  8337. this._transport = null;
  8338. if (this._worker) {
  8339. this._worker.destroy();
  8340. this._worker = null;
  8341. }
  8342. }.bind(this));
  8343. },
  8344. /**
  8345. * Registers callbacks to indicate the document loading completion.
  8346. *
  8347. * @param {function} onFulfilled The callback for the loading completion.
  8348. * @param {function} onRejected The callback for the loading failure.
  8349. * @return {Promise} A promise that is resolved after the onFulfilled or
  8350. * onRejected callback.
  8351. */
  8352. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8353. return this.promise.then.apply(this.promise, arguments);
  8354. }
  8355. };
  8356. return PDFDocumentLoadingTask;
  8357. })();
  8358. /**
  8359. * Abstract class to support range requests file loading.
  8360. * @class
  8361. * @alias PDFDataRangeTransport
  8362. * @param {number} length
  8363. * @param {Uint8Array} initialData
  8364. */
  8365. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8366. function PDFDataRangeTransport(length, initialData) {
  8367. this.length = length;
  8368. this.initialData = initialData;
  8369. this._rangeListeners = [];
  8370. this._progressListeners = [];
  8371. this._progressiveReadListeners = [];
  8372. this._readyCapability = createPromiseCapability();
  8373. }
  8374. PDFDataRangeTransport.prototype =
  8375. /** @lends PDFDataRangeTransport.prototype */ {
  8376. addRangeListener:
  8377. function PDFDataRangeTransport_addRangeListener(listener) {
  8378. this._rangeListeners.push(listener);
  8379. },
  8380. addProgressListener:
  8381. function PDFDataRangeTransport_addProgressListener(listener) {
  8382. this._progressListeners.push(listener);
  8383. },
  8384. addProgressiveReadListener:
  8385. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8386. this._progressiveReadListeners.push(listener);
  8387. },
  8388. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8389. var listeners = this._rangeListeners;
  8390. for (var i = 0, n = listeners.length; i < n; ++i) {
  8391. listeners[i](begin, chunk);
  8392. }
  8393. },
  8394. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8395. this._readyCapability.promise.then(function () {
  8396. var listeners = this._progressListeners;
  8397. for (var i = 0, n = listeners.length; i < n; ++i) {
  8398. listeners[i](loaded);
  8399. }
  8400. }.bind(this));
  8401. },
  8402. onDataProgressiveRead:
  8403. function PDFDataRangeTransport_onDataProgress(chunk) {
  8404. this._readyCapability.promise.then(function () {
  8405. var listeners = this._progressiveReadListeners;
  8406. for (var i = 0, n = listeners.length; i < n; ++i) {
  8407. listeners[i](chunk);
  8408. }
  8409. }.bind(this));
  8410. },
  8411. transportReady: function PDFDataRangeTransport_transportReady() {
  8412. this._readyCapability.resolve();
  8413. },
  8414. requestDataRange:
  8415. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8416. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8417. },
  8418. abort: function PDFDataRangeTransport_abort() {
  8419. }
  8420. };
  8421. return PDFDataRangeTransport;
  8422. })();
  8423. /**
  8424. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8425. * properties that can be read synchronously.
  8426. * @class
  8427. * @alias PDFDocumentProxy
  8428. */
  8429. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8430. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8431. this.pdfInfo = pdfInfo;
  8432. this.transport = transport;
  8433. this.loadingTask = loadingTask;
  8434. }
  8435. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8436. /**
  8437. * @return {number} Total number of pages the PDF contains.
  8438. */
  8439. get numPages() {
  8440. return this.pdfInfo.numPages;
  8441. },
  8442. /**
  8443. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8444. * unique.
  8445. */
  8446. get fingerprint() {
  8447. return this.pdfInfo.fingerprint;
  8448. },
  8449. /**
  8450. * @param {number} pageNumber The page number to get. The first page is 1.
  8451. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8452. * object.
  8453. */
  8454. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8455. return this.transport.getPage(pageNumber);
  8456. },
  8457. /**
  8458. * @param {{num: number, gen: number}} ref The page reference. Must have
  8459. * the 'num' and 'gen' properties.
  8460. * @return {Promise} A promise that is resolved with the page index that is
  8461. * associated with the reference.
  8462. */
  8463. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8464. return this.transport.getPageIndex(ref);
  8465. },
  8466. /**
  8467. * @return {Promise} A promise that is resolved with a lookup table for
  8468. * mapping named destinations to reference numbers.
  8469. *
  8470. * This can be slow for large documents: use getDestination instead
  8471. */
  8472. getDestinations: function PDFDocumentProxy_getDestinations() {
  8473. return this.transport.getDestinations();
  8474. },
  8475. /**
  8476. * @param {string} id The named destination to get.
  8477. * @return {Promise} A promise that is resolved with all information
  8478. * of the given named destination.
  8479. */
  8480. getDestination: function PDFDocumentProxy_getDestination(id) {
  8481. return this.transport.getDestination(id);
  8482. },
  8483. /**
  8484. * @return {Promise} A promise that is resolved with:
  8485. * an Array containing the pageLabels that correspond to the pageIndexes,
  8486. * or `null` when no pageLabels are present in the PDF file.
  8487. */
  8488. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8489. return this.transport.getPageLabels();
  8490. },
  8491. /**
  8492. * @return {Promise} A promise that is resolved with a lookup table for
  8493. * mapping named attachments to their content.
  8494. */
  8495. getAttachments: function PDFDocumentProxy_getAttachments() {
  8496. return this.transport.getAttachments();
  8497. },
  8498. /**
  8499. * @return {Promise} A promise that is resolved with an array of all the
  8500. * JavaScript strings in the name tree.
  8501. */
  8502. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8503. return this.transport.getJavaScript();
  8504. },
  8505. /**
  8506. * @return {Promise} A promise that is resolved with an {Array} that is a
  8507. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8508. * [
  8509. * {
  8510. * title: string,
  8511. * bold: boolean,
  8512. * italic: boolean,
  8513. * color: rgb Uint8Array,
  8514. * dest: dest obj,
  8515. * url: string,
  8516. * items: array of more items like this
  8517. * },
  8518. * ...
  8519. * ].
  8520. */
  8521. getOutline: function PDFDocumentProxy_getOutline() {
  8522. return this.transport.getOutline();
  8523. },
  8524. /**
  8525. * @return {Promise} A promise that is resolved with an {Object} that has
  8526. * info and metadata properties. Info is an {Object} filled with anything
  8527. * available in the information dictionary and similarly metadata is a
  8528. * {Metadata} object with information from the metadata section of the PDF.
  8529. */
  8530. getMetadata: function PDFDocumentProxy_getMetadata() {
  8531. return this.transport.getMetadata();
  8532. },
  8533. /**
  8534. * @return {Promise} A promise that is resolved with a TypedArray that has
  8535. * the raw data from the PDF.
  8536. */
  8537. getData: function PDFDocumentProxy_getData() {
  8538. return this.transport.getData();
  8539. },
  8540. /**
  8541. * @return {Promise} A promise that is resolved when the document's data
  8542. * is loaded. It is resolved with an {Object} that contains the length
  8543. * property that indicates size of the PDF data in bytes.
  8544. */
  8545. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8546. return this.transport.downloadInfoCapability.promise;
  8547. },
  8548. /**
  8549. * @return {Promise} A promise this is resolved with current stats about
  8550. * document structures (see {@link PDFDocumentStats}).
  8551. */
  8552. getStats: function PDFDocumentProxy_getStats() {
  8553. return this.transport.getStats();
  8554. },
  8555. /**
  8556. * Cleans up resources allocated by the document, e.g. created @font-face.
  8557. */
  8558. cleanup: function PDFDocumentProxy_cleanup() {
  8559. this.transport.startCleanup();
  8560. },
  8561. /**
  8562. * Destroys current document instance and terminates worker.
  8563. */
  8564. destroy: function PDFDocumentProxy_destroy() {
  8565. return this.loadingTask.destroy();
  8566. }
  8567. };
  8568. return PDFDocumentProxy;
  8569. })();
  8570. /**
  8571. * Page getTextContent parameters.
  8572. *
  8573. * @typedef {Object} getTextContentParameters
  8574. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8575. * whitespace with standard spaces (0x20). The default value is `false`.
  8576. * @param {boolean} disableCombineTextItems - do not attempt to combine
  8577. * same line {@link TextItem}'s. The default value is `false`.
  8578. */
  8579. /**
  8580. * Page text content.
  8581. *
  8582. * @typedef {Object} TextContent
  8583. * @property {array} items - array of {@link TextItem}
  8584. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8585. * name.
  8586. */
  8587. /**
  8588. * Page text content part.
  8589. *
  8590. * @typedef {Object} TextItem
  8591. * @property {string} str - text content.
  8592. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8593. * @property {array} transform - transformation matrix.
  8594. * @property {number} width - width in device space.
  8595. * @property {number} height - height in device space.
  8596. * @property {string} fontName - font name used by pdf.js for converted font.
  8597. */
  8598. /**
  8599. * Text style.
  8600. *
  8601. * @typedef {Object} TextStyle
  8602. * @property {number} ascent - font ascent.
  8603. * @property {number} descent - font descent.
  8604. * @property {boolean} vertical - text is in vertical mode.
  8605. * @property {string} fontFamily - possible font family
  8606. */
  8607. /**
  8608. * Page annotation parameters.
  8609. *
  8610. * @typedef {Object} GetAnnotationsParameters
  8611. * @param {string} intent - Determines the annotations that will be fetched,
  8612. * can be either 'display' (viewable annotations) or 'print'
  8613. * (printable annotations).
  8614. * If the parameter is omitted, all annotations are fetched.
  8615. */
  8616. /**
  8617. * Page render parameters.
  8618. *
  8619. * @typedef {Object} RenderParameters
  8620. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8621. * @property {PageViewport} viewport - Rendering viewport obtained by
  8622. * calling of PDFPage.getViewport method.
  8623. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8624. * (default value is 'display').
  8625. * @property {Array} transform - (optional) Additional transform, applied
  8626. * just before viewport transform.
  8627. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8628. * endLayout and appendImage functions.
  8629. * @property {function} continueCallback - (deprecated) A function that will be
  8630. * called each time the rendering is paused. To continue
  8631. * rendering call the function that is the first argument
  8632. * to the callback.
  8633. */
  8634. /**
  8635. * PDF page operator list.
  8636. *
  8637. * @typedef {Object} PDFOperatorList
  8638. * @property {Array} fnArray - Array containing the operator functions.
  8639. * @property {Array} argsArray - Array containing the arguments of the
  8640. * functions.
  8641. */
  8642. /**
  8643. * Proxy to a PDFPage in the worker thread.
  8644. * @class
  8645. * @alias PDFPageProxy
  8646. */
  8647. var PDFPageProxy = (function PDFPageProxyClosure() {
  8648. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8649. this.pageIndex = pageIndex;
  8650. this.pageInfo = pageInfo;
  8651. this.transport = transport;
  8652. this.stats = new StatTimer();
  8653. this.stats.enabled = getDefaultSetting('enableStats');
  8654. this.commonObjs = transport.commonObjs;
  8655. this.objs = new PDFObjects();
  8656. this.cleanupAfterRender = false;
  8657. this.pendingCleanup = false;
  8658. this.intentStates = Object.create(null);
  8659. this.destroyed = false;
  8660. }
  8661. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8662. /**
  8663. * @return {number} Page number of the page. First page is 1.
  8664. */
  8665. get pageNumber() {
  8666. return this.pageIndex + 1;
  8667. },
  8668. /**
  8669. * @return {number} The number of degrees the page is rotated clockwise.
  8670. */
  8671. get rotate() {
  8672. return this.pageInfo.rotate;
  8673. },
  8674. /**
  8675. * @return {Object} The reference that points to this page. It has 'num' and
  8676. * 'gen' properties.
  8677. */
  8678. get ref() {
  8679. return this.pageInfo.ref;
  8680. },
  8681. /**
  8682. * @return {Array} An array of the visible portion of the PDF page in the
  8683. * user space units - [x1, y1, x2, y2].
  8684. */
  8685. get view() {
  8686. return this.pageInfo.view;
  8687. },
  8688. /**
  8689. * @param {number} scale The desired scale of the viewport.
  8690. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8691. * defaults to the page rotation.
  8692. * @return {PageViewport} Contains 'width' and 'height' properties
  8693. * along with transforms required for rendering.
  8694. */
  8695. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8696. if (arguments.length < 2) {
  8697. rotate = this.rotate;
  8698. }
  8699. return new PageViewport(this.view, scale, rotate, 0, 0);
  8700. },
  8701. /**
  8702. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8703. * @return {Promise} A promise that is resolved with an {Array} of the
  8704. * annotation objects.
  8705. */
  8706. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8707. var intent = (params && params.intent) || null;
  8708. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8709. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8710. intent);
  8711. this.annotationsIntent = intent;
  8712. }
  8713. return this.annotationsPromise;
  8714. },
  8715. /**
  8716. * Begins the process of rendering a page to the desired context.
  8717. * @param {RenderParameters} params Page render parameters.
  8718. * @return {RenderTask} An object that contains the promise, which
  8719. * is resolved when the page finishes rendering.
  8720. */
  8721. render: function PDFPageProxy_render(params) {
  8722. var stats = this.stats;
  8723. stats.time('Overall');
  8724. // If there was a pending destroy cancel it so no cleanup happens during
  8725. // this call to render.
  8726. this.pendingCleanup = false;
  8727. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8728. if (!this.intentStates[renderingIntent]) {
  8729. this.intentStates[renderingIntent] = Object.create(null);
  8730. }
  8731. var intentState = this.intentStates[renderingIntent];
  8732. // If there's no displayReadyCapability yet, then the operatorList
  8733. // was never requested before. Make the request and create the promise.
  8734. if (!intentState.displayReadyCapability) {
  8735. intentState.receivingOperatorList = true;
  8736. intentState.displayReadyCapability = createPromiseCapability();
  8737. intentState.operatorList = {
  8738. fnArray: [],
  8739. argsArray: [],
  8740. lastChunk: false
  8741. };
  8742. this.stats.time('Page Request');
  8743. this.transport.messageHandler.send('RenderPageRequest', {
  8744. pageIndex: this.pageNumber - 1,
  8745. intent: renderingIntent
  8746. });
  8747. }
  8748. var internalRenderTask = new InternalRenderTask(complete, params,
  8749. this.objs,
  8750. this.commonObjs,
  8751. intentState.operatorList,
  8752. this.pageNumber);
  8753. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8754. if (!intentState.renderTasks) {
  8755. intentState.renderTasks = [];
  8756. }
  8757. intentState.renderTasks.push(internalRenderTask);
  8758. var renderTask = internalRenderTask.task;
  8759. // Obsolete parameter support
  8760. if (params.continueCallback) {
  8761. deprecated('render is used with continueCallback parameter');
  8762. renderTask.onContinue = params.continueCallback;
  8763. }
  8764. var self = this;
  8765. intentState.displayReadyCapability.promise.then(
  8766. function pageDisplayReadyPromise(transparency) {
  8767. if (self.pendingCleanup) {
  8768. complete();
  8769. return;
  8770. }
  8771. stats.time('Rendering');
  8772. internalRenderTask.initializeGraphics(transparency);
  8773. internalRenderTask.operatorListChanged();
  8774. },
  8775. function pageDisplayReadPromiseError(reason) {
  8776. complete(reason);
  8777. }
  8778. );
  8779. function complete(error) {
  8780. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8781. if (i >= 0) {
  8782. intentState.renderTasks.splice(i, 1);
  8783. }
  8784. if (self.cleanupAfterRender) {
  8785. self.pendingCleanup = true;
  8786. }
  8787. self._tryCleanup();
  8788. if (error) {
  8789. internalRenderTask.capability.reject(error);
  8790. } else {
  8791. internalRenderTask.capability.resolve();
  8792. }
  8793. stats.timeEnd('Rendering');
  8794. stats.timeEnd('Overall');
  8795. }
  8796. return renderTask;
  8797. },
  8798. /**
  8799. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8800. * object that represents page's operator list.
  8801. */
  8802. getOperatorList: function PDFPageProxy_getOperatorList() {
  8803. function operatorListChanged() {
  8804. if (intentState.operatorList.lastChunk) {
  8805. intentState.opListReadCapability.resolve(intentState.operatorList);
  8806. var i = intentState.renderTasks.indexOf(opListTask);
  8807. if (i >= 0) {
  8808. intentState.renderTasks.splice(i, 1);
  8809. }
  8810. }
  8811. }
  8812. var renderingIntent = 'oplist';
  8813. if (!this.intentStates[renderingIntent]) {
  8814. this.intentStates[renderingIntent] = Object.create(null);
  8815. }
  8816. var intentState = this.intentStates[renderingIntent];
  8817. var opListTask;
  8818. if (!intentState.opListReadCapability) {
  8819. opListTask = {};
  8820. opListTask.operatorListChanged = operatorListChanged;
  8821. intentState.receivingOperatorList = true;
  8822. intentState.opListReadCapability = createPromiseCapability();
  8823. intentState.renderTasks = [];
  8824. intentState.renderTasks.push(opListTask);
  8825. intentState.operatorList = {
  8826. fnArray: [],
  8827. argsArray: [],
  8828. lastChunk: false
  8829. };
  8830. this.transport.messageHandler.send('RenderPageRequest', {
  8831. pageIndex: this.pageIndex,
  8832. intent: renderingIntent
  8833. });
  8834. }
  8835. return intentState.opListReadCapability.promise;
  8836. },
  8837. /**
  8838. * @param {getTextContentParameters} params - getTextContent parameters.
  8839. * @return {Promise} That is resolved a {@link TextContent}
  8840. * object that represent the page text content.
  8841. */
  8842. getTextContent: function PDFPageProxy_getTextContent(params) {
  8843. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8844. pageIndex: this.pageNumber - 1,
  8845. normalizeWhitespace: (params && params.normalizeWhitespace === true ?
  8846. true : /* Default */ false),
  8847. combineTextItems: (params && params.disableCombineTextItems === true ?
  8848. false : /* Default */ true),
  8849. });
  8850. },
  8851. /**
  8852. * Destroys page object.
  8853. */
  8854. _destroy: function PDFPageProxy_destroy() {
  8855. this.destroyed = true;
  8856. this.transport.pageCache[this.pageIndex] = null;
  8857. var waitOn = [];
  8858. Object.keys(this.intentStates).forEach(function(intent) {
  8859. if (intent === 'oplist') {
  8860. // Avoid errors below, since the renderTasks are just stubs.
  8861. return;
  8862. }
  8863. var intentState = this.intentStates[intent];
  8864. intentState.renderTasks.forEach(function(renderTask) {
  8865. var renderCompleted = renderTask.capability.promise.
  8866. catch(function () {}); // ignoring failures
  8867. waitOn.push(renderCompleted);
  8868. renderTask.cancel();
  8869. });
  8870. }, this);
  8871. this.objs.clear();
  8872. this.annotationsPromise = null;
  8873. this.pendingCleanup = false;
  8874. return Promise.all(waitOn);
  8875. },
  8876. /**
  8877. * Cleans up resources allocated by the page. (deprecated)
  8878. */
  8879. destroy: function() {
  8880. deprecated('page destroy method, use cleanup() instead');
  8881. this.cleanup();
  8882. },
  8883. /**
  8884. * Cleans up resources allocated by the page.
  8885. */
  8886. cleanup: function PDFPageProxy_cleanup() {
  8887. this.pendingCleanup = true;
  8888. this._tryCleanup();
  8889. },
  8890. /**
  8891. * For internal use only. Attempts to clean up if rendering is in a state
  8892. * where that's possible.
  8893. * @ignore
  8894. */
  8895. _tryCleanup: function PDFPageProxy_tryCleanup() {
  8896. if (!this.pendingCleanup ||
  8897. Object.keys(this.intentStates).some(function(intent) {
  8898. var intentState = this.intentStates[intent];
  8899. return (intentState.renderTasks.length !== 0 ||
  8900. intentState.receivingOperatorList);
  8901. }, this)) {
  8902. return;
  8903. }
  8904. Object.keys(this.intentStates).forEach(function(intent) {
  8905. delete this.intentStates[intent];
  8906. }, this);
  8907. this.objs.clear();
  8908. this.annotationsPromise = null;
  8909. this.pendingCleanup = false;
  8910. },
  8911. /**
  8912. * For internal use only.
  8913. * @ignore
  8914. */
  8915. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  8916. intent) {
  8917. var intentState = this.intentStates[intent];
  8918. // TODO Refactor RenderPageRequest to separate rendering
  8919. // and operator list logic
  8920. if (intentState.displayReadyCapability) {
  8921. intentState.displayReadyCapability.resolve(transparency);
  8922. }
  8923. },
  8924. /**
  8925. * For internal use only.
  8926. * @ignore
  8927. */
  8928. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  8929. intent) {
  8930. var intentState = this.intentStates[intent];
  8931. var i, ii;
  8932. // Add the new chunk to the current operator list.
  8933. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  8934. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  8935. intentState.operatorList.argsArray.push(
  8936. operatorListChunk.argsArray[i]);
  8937. }
  8938. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  8939. // Notify all the rendering tasks there are more operators to be consumed.
  8940. for (i = 0; i < intentState.renderTasks.length; i++) {
  8941. intentState.renderTasks[i].operatorListChanged();
  8942. }
  8943. if (operatorListChunk.lastChunk) {
  8944. intentState.receivingOperatorList = false;
  8945. this._tryCleanup();
  8946. }
  8947. }
  8948. };
  8949. return PDFPageProxy;
  8950. })();
  8951. /**
  8952. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  8953. * WorkerTransport for them. If creation of a web worker is not possible,
  8954. * a "fake" worker will be used instead.
  8955. * @class
  8956. */
  8957. var PDFWorker = (function PDFWorkerClosure() {
  8958. var nextFakeWorkerId = 0;
  8959. function getWorkerSrc() {
  8960. if (typeof workerSrc !== 'undefined') {
  8961. return workerSrc;
  8962. }
  8963. if (getDefaultSetting('workerSrc')) {
  8964. return getDefaultSetting('workerSrc');
  8965. }
  8966. if (pdfjsFilePath) {
  8967. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  8968. }
  8969. error('No PDFJS.workerSrc specified');
  8970. }
  8971. var fakeWorkerFilesLoadedCapability;
  8972. // Loads worker code into main thread.
  8973. function setupFakeWorkerGlobal() {
  8974. var WorkerMessageHandler;
  8975. if (!fakeWorkerFilesLoadedCapability) {
  8976. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  8977. // In the developer build load worker_loader which in turn loads all the
  8978. // other files and resolves the promise. In production only the
  8979. // pdf.worker.js file is needed.
  8980. var loader = fakeWorkerFilesLoader || function (callback) {
  8981. Util.loadScript(getWorkerSrc(), function () {
  8982. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  8983. });
  8984. };
  8985. loader(fakeWorkerFilesLoadedCapability.resolve);
  8986. }
  8987. return fakeWorkerFilesLoadedCapability.promise;
  8988. }
  8989. function createCDNWrapper(url) {
  8990. // We will rely on blob URL's property to specify origin.
  8991. // We want this function to fail in case if createObjectURL or Blob do not
  8992. // exist or fail for some reason -- our Worker creation will fail anyway.
  8993. var wrapper = 'importScripts(\'' + url + '\');';
  8994. return URL.createObjectURL(new Blob([wrapper]));
  8995. }
  8996. function PDFWorker(name) {
  8997. this.name = name;
  8998. this.destroyed = false;
  8999. this._readyCapability = createPromiseCapability();
  9000. this._port = null;
  9001. this._webWorker = null;
  9002. this._messageHandler = null;
  9003. this._initialize();
  9004. }
  9005. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  9006. get promise() {
  9007. return this._readyCapability.promise;
  9008. },
  9009. get port() {
  9010. return this._port;
  9011. },
  9012. get messageHandler() {
  9013. return this._messageHandler;
  9014. },
  9015. _initialize: function PDFWorker_initialize() {
  9016. // If worker support isn't disabled explicit and the browser has worker
  9017. // support, create a new web worker and test if it/the browser fulfills
  9018. // all requirements to run parts of pdf.js in a web worker.
  9019. // Right now, the requirement is, that an Uint8Array is still an
  9020. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9021. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') &&
  9022. typeof Worker !== 'undefined') {
  9023. var workerSrc = getWorkerSrc();
  9024. try {
  9025. // Wraps workerSrc path into blob URL, if the former does not belong
  9026. // to the same origin.
  9027. if (!isSameOrigin(window.location.href, workerSrc)) {
  9028. workerSrc = createCDNWrapper(
  9029. new URL(workerSrc, window.location).href);
  9030. }
  9031. // Some versions of FF can't create a worker on localhost, see:
  9032. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9033. var worker = new Worker(workerSrc);
  9034. var messageHandler = new MessageHandler('main', 'worker', worker);
  9035. var terminateEarly = function() {
  9036. worker.removeEventListener('error', onWorkerError);
  9037. messageHandler.destroy();
  9038. worker.terminate();
  9039. if (this.destroyed) {
  9040. this._readyCapability.reject(new Error('Worker was destroyed'));
  9041. } else {
  9042. // Fall back to fake worker if the termination is caused by an
  9043. // error (e.g. NetworkError / SecurityError).
  9044. this._setupFakeWorker();
  9045. }
  9046. }.bind(this);
  9047. var onWorkerError = function(event) {
  9048. if (!this._webWorker) {
  9049. // Worker failed to initialize due to an error. Clean up and fall
  9050. // back to the fake worker.
  9051. terminateEarly();
  9052. }
  9053. }.bind(this);
  9054. worker.addEventListener('error', onWorkerError);
  9055. messageHandler.on('test', function PDFWorker_test(data) {
  9056. worker.removeEventListener('error', onWorkerError);
  9057. if (this.destroyed) {
  9058. terminateEarly();
  9059. return; // worker was destroyed
  9060. }
  9061. var supportTypedArray = data && data.supportTypedArray;
  9062. if (supportTypedArray) {
  9063. this._messageHandler = messageHandler;
  9064. this._port = worker;
  9065. this._webWorker = worker;
  9066. if (!data.supportTransfers) {
  9067. isPostMessageTransfersDisabled = true;
  9068. }
  9069. this._readyCapability.resolve();
  9070. // Send global setting, e.g. verbosity level.
  9071. messageHandler.send('configure', {
  9072. verbosity: getVerbosityLevel()
  9073. });
  9074. } else {
  9075. this._setupFakeWorker();
  9076. messageHandler.destroy();
  9077. worker.terminate();
  9078. }
  9079. }.bind(this));
  9080. messageHandler.on('console_log', function (data) {
  9081. console.log.apply(console, data);
  9082. });
  9083. messageHandler.on('console_error', function (data) {
  9084. console.error.apply(console, data);
  9085. });
  9086. messageHandler.on('ready', function (data) {
  9087. worker.removeEventListener('error', onWorkerError);
  9088. if (this.destroyed) {
  9089. terminateEarly();
  9090. return; // worker was destroyed
  9091. }
  9092. try {
  9093. sendTest();
  9094. } catch (e) {
  9095. // We need fallback to a faked worker.
  9096. this._setupFakeWorker();
  9097. }
  9098. }.bind(this));
  9099. var sendTest = function () {
  9100. var postMessageTransfers =
  9101. getDefaultSetting('postMessageTransfers') &&
  9102. !isPostMessageTransfersDisabled;
  9103. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9104. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9105. // typed array. Also, checking if we can use transfers.
  9106. try {
  9107. messageHandler.send('test', testObj, [testObj.buffer]);
  9108. } catch (ex) {
  9109. info('Cannot use postMessage transfers');
  9110. testObj[0] = 0;
  9111. messageHandler.send('test', testObj);
  9112. }
  9113. };
  9114. // It might take time for worker to initialize (especially when AMD
  9115. // loader is used). We will try to send test immediately, and then
  9116. // when 'ready' message will arrive. The worker shall process only
  9117. // first received 'test'.
  9118. sendTest();
  9119. return;
  9120. } catch (e) {
  9121. info('The worker has been disabled.');
  9122. }
  9123. }
  9124. // Either workers are disabled, not supported or have thrown an exception.
  9125. // Thus, we fallback to a faked worker.
  9126. this._setupFakeWorker();
  9127. },
  9128. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9129. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9130. warn('Setting up fake worker.');
  9131. isWorkerDisabled = true;
  9132. }
  9133. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9134. if (this.destroyed) {
  9135. this._readyCapability.reject(new Error('Worker was destroyed'));
  9136. return;
  9137. }
  9138. // If we don't use a worker, just post/sendMessage to the main thread.
  9139. var port = {
  9140. _listeners: [],
  9141. postMessage: function (obj) {
  9142. var e = {data: obj};
  9143. this._listeners.forEach(function (listener) {
  9144. listener.call(this, e);
  9145. }, this);
  9146. },
  9147. addEventListener: function (name, listener) {
  9148. this._listeners.push(listener);
  9149. },
  9150. removeEventListener: function (name, listener) {
  9151. var i = this._listeners.indexOf(listener);
  9152. this._listeners.splice(i, 1);
  9153. },
  9154. terminate: function () {}
  9155. };
  9156. this._port = port;
  9157. // All fake workers use the same port, making id unique.
  9158. var id = 'fake' + (nextFakeWorkerId++);
  9159. // If the main thread is our worker, setup the handling for the
  9160. // messages -- the main thread sends to it self.
  9161. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9162. WorkerMessageHandler.setup(workerHandler, port);
  9163. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9164. this._messageHandler = messageHandler;
  9165. this._readyCapability.resolve();
  9166. }.bind(this));
  9167. },
  9168. /**
  9169. * Destroys the worker instance.
  9170. */
  9171. destroy: function PDFWorker_destroy() {
  9172. this.destroyed = true;
  9173. if (this._webWorker) {
  9174. // We need to terminate only web worker created resource.
  9175. this._webWorker.terminate();
  9176. this._webWorker = null;
  9177. }
  9178. this._port = null;
  9179. if (this._messageHandler) {
  9180. this._messageHandler.destroy();
  9181. this._messageHandler = null;
  9182. }
  9183. }
  9184. };
  9185. return PDFWorker;
  9186. })();
  9187. /**
  9188. * For internal use only.
  9189. * @ignore
  9190. */
  9191. var WorkerTransport = (function WorkerTransportClosure() {
  9192. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9193. this.messageHandler = messageHandler;
  9194. this.loadingTask = loadingTask;
  9195. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9196. this.commonObjs = new PDFObjects();
  9197. this.fontLoader = new FontLoader(loadingTask.docId);
  9198. this.destroyed = false;
  9199. this.destroyCapability = null;
  9200. this.pageCache = [];
  9201. this.pagePromises = [];
  9202. this.downloadInfoCapability = createPromiseCapability();
  9203. this.setupMessageHandler();
  9204. }
  9205. WorkerTransport.prototype = {
  9206. destroy: function WorkerTransport_destroy() {
  9207. if (this.destroyCapability) {
  9208. return this.destroyCapability.promise;
  9209. }
  9210. this.destroyed = true;
  9211. this.destroyCapability = createPromiseCapability();
  9212. var waitOn = [];
  9213. // We need to wait for all renderings to be completed, e.g.
  9214. // timeout/rAF can take a long time.
  9215. this.pageCache.forEach(function (page) {
  9216. if (page) {
  9217. waitOn.push(page._destroy());
  9218. }
  9219. });
  9220. this.pageCache = [];
  9221. this.pagePromises = [];
  9222. var self = this;
  9223. // We also need to wait for the worker to finish its long running tasks.
  9224. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9225. waitOn.push(terminated);
  9226. Promise.all(waitOn).then(function () {
  9227. self.fontLoader.clear();
  9228. if (self.pdfDataRangeTransport) {
  9229. self.pdfDataRangeTransport.abort();
  9230. self.pdfDataRangeTransport = null;
  9231. }
  9232. if (self.messageHandler) {
  9233. self.messageHandler.destroy();
  9234. self.messageHandler = null;
  9235. }
  9236. self.destroyCapability.resolve();
  9237. }, this.destroyCapability.reject);
  9238. return this.destroyCapability.promise;
  9239. },
  9240. setupMessageHandler:
  9241. function WorkerTransport_setupMessageHandler() {
  9242. var messageHandler = this.messageHandler;
  9243. function updatePassword(password) {
  9244. messageHandler.send('UpdatePassword', password);
  9245. }
  9246. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9247. if (pdfDataRangeTransport) {
  9248. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  9249. messageHandler.send('OnDataRange', {
  9250. begin: begin,
  9251. chunk: chunk
  9252. });
  9253. });
  9254. pdfDataRangeTransport.addProgressListener(function(loaded) {
  9255. messageHandler.send('OnDataProgress', {
  9256. loaded: loaded
  9257. });
  9258. });
  9259. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  9260. messageHandler.send('OnDataRange', {
  9261. chunk: chunk
  9262. });
  9263. });
  9264. messageHandler.on('RequestDataRange',
  9265. function transportDataRange(data) {
  9266. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9267. }, this);
  9268. }
  9269. messageHandler.on('GetDoc', function transportDoc(data) {
  9270. var pdfInfo = data.pdfInfo;
  9271. this.numPages = data.pdfInfo.numPages;
  9272. var loadingTask = this.loadingTask;
  9273. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9274. this.pdfDocument = pdfDocument;
  9275. loadingTask._capability.resolve(pdfDocument);
  9276. }, this);
  9277. messageHandler.on('NeedPassword',
  9278. function transportNeedPassword(exception) {
  9279. var loadingTask = this.loadingTask;
  9280. if (loadingTask.onPassword) {
  9281. return loadingTask.onPassword(updatePassword,
  9282. PasswordResponses.NEED_PASSWORD);
  9283. }
  9284. loadingTask._capability.reject(
  9285. new PasswordException(exception.message, exception.code));
  9286. }, this);
  9287. messageHandler.on('IncorrectPassword',
  9288. function transportIncorrectPassword(exception) {
  9289. var loadingTask = this.loadingTask;
  9290. if (loadingTask.onPassword) {
  9291. return loadingTask.onPassword(updatePassword,
  9292. PasswordResponses.INCORRECT_PASSWORD);
  9293. }
  9294. loadingTask._capability.reject(
  9295. new PasswordException(exception.message, exception.code));
  9296. }, this);
  9297. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9298. this.loadingTask._capability.reject(
  9299. new InvalidPDFException(exception.message));
  9300. }, this);
  9301. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9302. this.loadingTask._capability.reject(
  9303. new MissingPDFException(exception.message));
  9304. }, this);
  9305. messageHandler.on('UnexpectedResponse',
  9306. function transportUnexpectedResponse(exception) {
  9307. this.loadingTask._capability.reject(
  9308. new UnexpectedResponseException(exception.message, exception.status));
  9309. }, this);
  9310. messageHandler.on('UnknownError',
  9311. function transportUnknownError(exception) {
  9312. this.loadingTask._capability.reject(
  9313. new UnknownErrorException(exception.message, exception.details));
  9314. }, this);
  9315. messageHandler.on('DataLoaded', function transportPage(data) {
  9316. this.downloadInfoCapability.resolve(data);
  9317. }, this);
  9318. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9319. if (this.pdfDataRangeTransport) {
  9320. this.pdfDataRangeTransport.transportReady();
  9321. }
  9322. }, this);
  9323. messageHandler.on('StartRenderPage', function transportRender(data) {
  9324. if (this.destroyed) {
  9325. return; // Ignore any pending requests if the worker was terminated.
  9326. }
  9327. var page = this.pageCache[data.pageIndex];
  9328. page.stats.timeEnd('Page Request');
  9329. page._startRenderPage(data.transparency, data.intent);
  9330. }, this);
  9331. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9332. if (this.destroyed) {
  9333. return; // Ignore any pending requests if the worker was terminated.
  9334. }
  9335. var page = this.pageCache[data.pageIndex];
  9336. page._renderPageChunk(data.operatorList, data.intent);
  9337. }, this);
  9338. messageHandler.on('commonobj', function transportObj(data) {
  9339. if (this.destroyed) {
  9340. return; // Ignore any pending requests if the worker was terminated.
  9341. }
  9342. var id = data[0];
  9343. var type = data[1];
  9344. if (this.commonObjs.hasData(id)) {
  9345. return;
  9346. }
  9347. switch (type) {
  9348. case 'Font':
  9349. var exportedData = data[2];
  9350. if ('error' in exportedData) {
  9351. var exportedError = exportedData.error;
  9352. warn('Error during font loading: ' + exportedError);
  9353. this.commonObjs.resolve(id, exportedError);
  9354. break;
  9355. }
  9356. var fontRegistry = null;
  9357. if (getDefaultSetting('pdfBug') && globalScope.FontInspector &&
  9358. globalScope['FontInspector'].enabled) {
  9359. fontRegistry = {
  9360. registerFont: function (font, url) {
  9361. globalScope['FontInspector'].fontAdded(font, url);
  9362. }
  9363. };
  9364. }
  9365. var font = new FontFaceObject(exportedData, {
  9366. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9367. disableFontFace: getDefaultSetting('disableFontFace'),
  9368. fontRegistry: fontRegistry
  9369. });
  9370. this.fontLoader.bind(
  9371. [font],
  9372. function fontReady(fontObjs) {
  9373. this.commonObjs.resolve(id, font);
  9374. }.bind(this)
  9375. );
  9376. break;
  9377. case 'FontPath':
  9378. this.commonObjs.resolve(id, data[2]);
  9379. break;
  9380. default:
  9381. error('Got unknown common object type ' + type);
  9382. }
  9383. }, this);
  9384. messageHandler.on('obj', function transportObj(data) {
  9385. if (this.destroyed) {
  9386. return; // Ignore any pending requests if the worker was terminated.
  9387. }
  9388. var id = data[0];
  9389. var pageIndex = data[1];
  9390. var type = data[2];
  9391. var pageProxy = this.pageCache[pageIndex];
  9392. var imageData;
  9393. if (pageProxy.objs.hasData(id)) {
  9394. return;
  9395. }
  9396. switch (type) {
  9397. case 'JpegStream':
  9398. imageData = data[3];
  9399. loadJpegStream(id, imageData, pageProxy.objs);
  9400. break;
  9401. case 'Image':
  9402. imageData = data[3];
  9403. pageProxy.objs.resolve(id, imageData);
  9404. // heuristics that will allow not to store large data
  9405. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9406. if (imageData && 'data' in imageData &&
  9407. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9408. pageProxy.cleanupAfterRender = true;
  9409. }
  9410. break;
  9411. default:
  9412. error('Got unknown object type ' + type);
  9413. }
  9414. }, this);
  9415. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9416. if (this.destroyed) {
  9417. return; // Ignore any pending requests if the worker was terminated.
  9418. }
  9419. var loadingTask = this.loadingTask;
  9420. if (loadingTask.onProgress) {
  9421. loadingTask.onProgress({
  9422. loaded: data.loaded,
  9423. total: data.total
  9424. });
  9425. }
  9426. }, this);
  9427. messageHandler.on('PageError', function transportError(data) {
  9428. if (this.destroyed) {
  9429. return; // Ignore any pending requests if the worker was terminated.
  9430. }
  9431. var page = this.pageCache[data.pageNum - 1];
  9432. var intentState = page.intentStates[data.intent];
  9433. if (intentState.displayReadyCapability) {
  9434. intentState.displayReadyCapability.reject(data.error);
  9435. } else {
  9436. error(data.error);
  9437. }
  9438. if (intentState.operatorList) {
  9439. // Mark operator list as complete.
  9440. intentState.operatorList.lastChunk = true;
  9441. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9442. intentState.renderTasks[i].operatorListChanged();
  9443. }
  9444. }
  9445. }, this);
  9446. messageHandler.on('UnsupportedFeature',
  9447. function transportUnsupportedFeature(data) {
  9448. if (this.destroyed) {
  9449. return; // Ignore any pending requests if the worker was terminated.
  9450. }
  9451. var featureId = data.featureId;
  9452. var loadingTask = this.loadingTask;
  9453. if (loadingTask.onUnsupportedFeature) {
  9454. loadingTask.onUnsupportedFeature(featureId);
  9455. }
  9456. _UnsupportedManager.notify(featureId);
  9457. }, this);
  9458. messageHandler.on('JpegDecode', function(data) {
  9459. if (this.destroyed) {
  9460. return Promise.reject(new Error('Worker was destroyed'));
  9461. }
  9462. var imageUrl = data[0];
  9463. var components = data[1];
  9464. if (components !== 3 && components !== 1) {
  9465. return Promise.reject(
  9466. new Error('Only 3 components or 1 component can be returned'));
  9467. }
  9468. return new Promise(function (resolve, reject) {
  9469. var img = new Image();
  9470. img.onload = function () {
  9471. var width = img.width;
  9472. var height = img.height;
  9473. var size = width * height;
  9474. var rgbaLength = size * 4;
  9475. var buf = new Uint8Array(size * components);
  9476. var tmpCanvas = createScratchCanvas(width, height);
  9477. var tmpCtx = tmpCanvas.getContext('2d');
  9478. tmpCtx.drawImage(img, 0, 0);
  9479. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9480. var i, j;
  9481. if (components === 3) {
  9482. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9483. buf[j] = data[i];
  9484. buf[j + 1] = data[i + 1];
  9485. buf[j + 2] = data[i + 2];
  9486. }
  9487. } else if (components === 1) {
  9488. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9489. buf[j] = data[i];
  9490. }
  9491. }
  9492. resolve({ data: buf, width: width, height: height});
  9493. };
  9494. img.onerror = function () {
  9495. reject(new Error('JpegDecode failed to load image'));
  9496. };
  9497. img.src = imageUrl;
  9498. });
  9499. }, this);
  9500. },
  9501. getData: function WorkerTransport_getData() {
  9502. return this.messageHandler.sendWithPromise('GetData', null);
  9503. },
  9504. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9505. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9506. return Promise.reject(new Error('Invalid page request'));
  9507. }
  9508. var pageIndex = pageNumber - 1;
  9509. if (pageIndex in this.pagePromises) {
  9510. return this.pagePromises[pageIndex];
  9511. }
  9512. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9513. pageIndex: pageIndex
  9514. }).then(function (pageInfo) {
  9515. if (this.destroyed) {
  9516. throw new Error('Transport destroyed');
  9517. }
  9518. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9519. this.pageCache[pageIndex] = page;
  9520. return page;
  9521. }.bind(this));
  9522. this.pagePromises[pageIndex] = promise;
  9523. return promise;
  9524. },
  9525. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9526. return this.messageHandler.sendWithPromise('GetPageIndex', {
  9527. ref: ref,
  9528. }).catch(function (reason) {
  9529. return Promise.reject(new Error(reason));
  9530. });
  9531. },
  9532. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9533. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9534. pageIndex: pageIndex,
  9535. intent: intent,
  9536. });
  9537. },
  9538. getDestinations: function WorkerTransport_getDestinations() {
  9539. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9540. },
  9541. getDestination: function WorkerTransport_getDestination(id) {
  9542. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9543. },
  9544. getPageLabels: function WorkerTransport_getPageLabels() {
  9545. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9546. },
  9547. getAttachments: function WorkerTransport_getAttachments() {
  9548. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9549. },
  9550. getJavaScript: function WorkerTransport_getJavaScript() {
  9551. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9552. },
  9553. getOutline: function WorkerTransport_getOutline() {
  9554. return this.messageHandler.sendWithPromise('GetOutline', null);
  9555. },
  9556. getMetadata: function WorkerTransport_getMetadata() {
  9557. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9558. then(function transportMetadata(results) {
  9559. return {
  9560. info: results[0],
  9561. metadata: (results[1] ? new Metadata(results[1]) : null)
  9562. };
  9563. });
  9564. },
  9565. getStats: function WorkerTransport_getStats() {
  9566. return this.messageHandler.sendWithPromise('GetStats', null);
  9567. },
  9568. startCleanup: function WorkerTransport_startCleanup() {
  9569. this.messageHandler.sendWithPromise('Cleanup', null).
  9570. then(function endCleanup() {
  9571. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9572. var page = this.pageCache[i];
  9573. if (page) {
  9574. page.cleanup();
  9575. }
  9576. }
  9577. this.commonObjs.clear();
  9578. this.fontLoader.clear();
  9579. }.bind(this));
  9580. }
  9581. };
  9582. return WorkerTransport;
  9583. })();
  9584. /**
  9585. * A PDF document and page is built of many objects. E.g. there are objects
  9586. * for fonts, images, rendering code and such. These objects might get processed
  9587. * inside of a worker. The `PDFObjects` implements some basic functions to
  9588. * manage these objects.
  9589. * @ignore
  9590. */
  9591. var PDFObjects = (function PDFObjectsClosure() {
  9592. function PDFObjects() {
  9593. this.objs = Object.create(null);
  9594. }
  9595. PDFObjects.prototype = {
  9596. /**
  9597. * Internal function.
  9598. * Ensures there is an object defined for `objId`.
  9599. */
  9600. ensureObj: function PDFObjects_ensureObj(objId) {
  9601. if (this.objs[objId]) {
  9602. return this.objs[objId];
  9603. }
  9604. var obj = {
  9605. capability: createPromiseCapability(),
  9606. data: null,
  9607. resolved: false
  9608. };
  9609. this.objs[objId] = obj;
  9610. return obj;
  9611. },
  9612. /**
  9613. * If called *without* callback, this returns the data of `objId` but the
  9614. * object needs to be resolved. If it isn't, this function throws.
  9615. *
  9616. * If called *with* a callback, the callback is called with the data of the
  9617. * object once the object is resolved. That means, if you call this
  9618. * function and the object is already resolved, the callback gets called
  9619. * right away.
  9620. */
  9621. get: function PDFObjects_get(objId, callback) {
  9622. // If there is a callback, then the get can be async and the object is
  9623. // not required to be resolved right now
  9624. if (callback) {
  9625. this.ensureObj(objId).capability.promise.then(callback);
  9626. return null;
  9627. }
  9628. // If there isn't a callback, the user expects to get the resolved data
  9629. // directly.
  9630. var obj = this.objs[objId];
  9631. // If there isn't an object yet or the object isn't resolved, then the
  9632. // data isn't ready yet!
  9633. if (!obj || !obj.resolved) {
  9634. error('Requesting object that isn\'t resolved yet ' + objId);
  9635. }
  9636. return obj.data;
  9637. },
  9638. /**
  9639. * Resolves the object `objId` with optional `data`.
  9640. */
  9641. resolve: function PDFObjects_resolve(objId, data) {
  9642. var obj = this.ensureObj(objId);
  9643. obj.resolved = true;
  9644. obj.data = data;
  9645. obj.capability.resolve(data);
  9646. },
  9647. isResolved: function PDFObjects_isResolved(objId) {
  9648. var objs = this.objs;
  9649. if (!objs[objId]) {
  9650. return false;
  9651. } else {
  9652. return objs[objId].resolved;
  9653. }
  9654. },
  9655. hasData: function PDFObjects_hasData(objId) {
  9656. return this.isResolved(objId);
  9657. },
  9658. /**
  9659. * Returns the data of `objId` if object exists, null otherwise.
  9660. */
  9661. getData: function PDFObjects_getData(objId) {
  9662. var objs = this.objs;
  9663. if (!objs[objId] || !objs[objId].resolved) {
  9664. return null;
  9665. } else {
  9666. return objs[objId].data;
  9667. }
  9668. },
  9669. clear: function PDFObjects_clear() {
  9670. this.objs = Object.create(null);
  9671. }
  9672. };
  9673. return PDFObjects;
  9674. })();
  9675. /**
  9676. * Allows controlling of the rendering tasks.
  9677. * @class
  9678. * @alias RenderTask
  9679. */
  9680. var RenderTask = (function RenderTaskClosure() {
  9681. function RenderTask(internalRenderTask) {
  9682. this._internalRenderTask = internalRenderTask;
  9683. /**
  9684. * Callback for incremental rendering -- a function that will be called
  9685. * each time the rendering is paused. To continue rendering call the
  9686. * function that is the first argument to the callback.
  9687. * @type {function}
  9688. */
  9689. this.onContinue = null;
  9690. }
  9691. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9692. /**
  9693. * Promise for rendering task completion.
  9694. * @return {Promise}
  9695. */
  9696. get promise() {
  9697. return this._internalRenderTask.capability.promise;
  9698. },
  9699. /**
  9700. * Cancels the rendering task. If the task is currently rendering it will
  9701. * not be cancelled until graphics pauses with a timeout. The promise that
  9702. * this object extends will resolved when cancelled.
  9703. */
  9704. cancel: function RenderTask_cancel() {
  9705. this._internalRenderTask.cancel();
  9706. },
  9707. /**
  9708. * Registers callbacks to indicate the rendering task completion.
  9709. *
  9710. * @param {function} onFulfilled The callback for the rendering completion.
  9711. * @param {function} onRejected The callback for the rendering failure.
  9712. * @return {Promise} A promise that is resolved after the onFulfilled or
  9713. * onRejected callback.
  9714. */
  9715. then: function RenderTask_then(onFulfilled, onRejected) {
  9716. return this.promise.then.apply(this.promise, arguments);
  9717. }
  9718. };
  9719. return RenderTask;
  9720. })();
  9721. /**
  9722. * For internal use only.
  9723. * @ignore
  9724. */
  9725. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9726. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9727. pageNumber) {
  9728. this.callback = callback;
  9729. this.params = params;
  9730. this.objs = objs;
  9731. this.commonObjs = commonObjs;
  9732. this.operatorListIdx = null;
  9733. this.operatorList = operatorList;
  9734. this.pageNumber = pageNumber;
  9735. this.running = false;
  9736. this.graphicsReadyCallback = null;
  9737. this.graphicsReady = false;
  9738. this.useRequestAnimationFrame = false;
  9739. this.cancelled = false;
  9740. this.capability = createPromiseCapability();
  9741. this.task = new RenderTask(this);
  9742. // caching this-bound methods
  9743. this._continueBound = this._continue.bind(this);
  9744. this._scheduleNextBound = this._scheduleNext.bind(this);
  9745. this._nextBound = this._next.bind(this);
  9746. }
  9747. InternalRenderTask.prototype = {
  9748. initializeGraphics:
  9749. function InternalRenderTask_initializeGraphics(transparency) {
  9750. if (this.cancelled) {
  9751. return;
  9752. }
  9753. if (getDefaultSetting('pdfBug') && globalScope.StepperManager &&
  9754. globalScope.StepperManager.enabled) {
  9755. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9756. this.stepper.init(this.operatorList);
  9757. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9758. }
  9759. var params = this.params;
  9760. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9761. this.objs, params.imageLayer);
  9762. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9763. this.operatorListIdx = 0;
  9764. this.graphicsReady = true;
  9765. if (this.graphicsReadyCallback) {
  9766. this.graphicsReadyCallback();
  9767. }
  9768. },
  9769. cancel: function InternalRenderTask_cancel() {
  9770. this.running = false;
  9771. this.cancelled = true;
  9772. this.callback('cancelled');
  9773. },
  9774. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9775. if (!this.graphicsReady) {
  9776. if (!this.graphicsReadyCallback) {
  9777. this.graphicsReadyCallback = this._continueBound;
  9778. }
  9779. return;
  9780. }
  9781. if (this.stepper) {
  9782. this.stepper.updateOperatorList(this.operatorList);
  9783. }
  9784. if (this.running) {
  9785. return;
  9786. }
  9787. this._continue();
  9788. },
  9789. _continue: function InternalRenderTask__continue() {
  9790. this.running = true;
  9791. if (this.cancelled) {
  9792. return;
  9793. }
  9794. if (this.task.onContinue) {
  9795. this.task.onContinue.call(this.task, this._scheduleNextBound);
  9796. } else {
  9797. this._scheduleNext();
  9798. }
  9799. },
  9800. _scheduleNext: function InternalRenderTask__scheduleNext() {
  9801. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  9802. window.requestAnimationFrame(this._nextBound);
  9803. } else {
  9804. Promise.resolve(undefined).then(this._nextBound);
  9805. }
  9806. },
  9807. _next: function InternalRenderTask__next() {
  9808. if (this.cancelled) {
  9809. return;
  9810. }
  9811. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  9812. this.operatorListIdx,
  9813. this._continueBound,
  9814. this.stepper);
  9815. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  9816. this.running = false;
  9817. if (this.operatorList.lastChunk) {
  9818. this.gfx.endDrawing();
  9819. this.callback();
  9820. }
  9821. }
  9822. }
  9823. };
  9824. return InternalRenderTask;
  9825. })();
  9826. /**
  9827. * (Deprecated) Global observer of unsupported feature usages. Use
  9828. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  9829. */
  9830. var _UnsupportedManager = (function UnsupportedManagerClosure() {
  9831. var listeners = [];
  9832. return {
  9833. listen: function (cb) {
  9834. deprecated('Global UnsupportedManager.listen is used: ' +
  9835. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  9836. listeners.push(cb);
  9837. },
  9838. notify: function (featureId) {
  9839. for (var i = 0, ii = listeners.length; i < ii; i++) {
  9840. listeners[i](featureId);
  9841. }
  9842. }
  9843. };
  9844. })();
  9845. if (typeof pdfjsVersion !== 'undefined') {
  9846. exports.version = pdfjsVersion;
  9847. }
  9848. if (typeof pdfjsBuild !== 'undefined') {
  9849. exports.build = pdfjsBuild;
  9850. }
  9851. exports.getDocument = getDocument;
  9852. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  9853. exports.PDFWorker = PDFWorker;
  9854. exports.PDFDocumentProxy = PDFDocumentProxy;
  9855. exports.PDFPageProxy = PDFPageProxy;
  9856. exports._UnsupportedManager = _UnsupportedManager;
  9857. }));
  9858. (function (root, factory) {
  9859. {
  9860. factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil,
  9861. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI,
  9862. root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer,
  9863. root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  9864. }
  9865. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI,
  9866. displayAnnotationLayer, displayTextLayer, displayMetadata,
  9867. displaySVG) {
  9868. var globalScope = sharedUtil.globalScope;
  9869. var deprecated = sharedUtil.deprecated;
  9870. var warn = sharedUtil.warn;
  9871. var LinkTarget = displayDOMUtils.LinkTarget;
  9872. var isWorker = (typeof window === 'undefined');
  9873. // The global PDFJS object is now deprecated and will not be supported in
  9874. // the future. The members below are maintained for backward compatibility
  9875. // and shall not be extended or modified. If the global.js is included as
  9876. // a module, we will create a global PDFJS object instance or use existing.
  9877. if (!globalScope.PDFJS) {
  9878. globalScope.PDFJS = {};
  9879. }
  9880. var PDFJS = globalScope.PDFJS;
  9881. if (typeof pdfjsVersion !== 'undefined') {
  9882. PDFJS.version = pdfjsVersion;
  9883. }
  9884. if (typeof pdfjsBuild !== 'undefined') {
  9885. PDFJS.build = pdfjsBuild;
  9886. }
  9887. PDFJS.pdfBug = false;
  9888. if (PDFJS.verbosity !== undefined) {
  9889. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  9890. }
  9891. delete PDFJS.verbosity;
  9892. Object.defineProperty(PDFJS, 'verbosity', {
  9893. get: function () { return sharedUtil.getVerbosityLevel(); },
  9894. set: function (level) { sharedUtil.setVerbosityLevel(level); },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  9899. PDFJS.OPS = sharedUtil.OPS;
  9900. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  9901. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  9902. PDFJS.shadow = sharedUtil.shadow;
  9903. PDFJS.createBlob = sharedUtil.createBlob;
  9904. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  9905. return sharedUtil.createObjectURL(data, contentType,
  9906. PDFJS.disableCreateObjectURL);
  9907. };
  9908. Object.defineProperty(PDFJS, 'isLittleEndian', {
  9909. configurable: true,
  9910. get: function PDFJS_isLittleEndian() {
  9911. var value = sharedUtil.isLittleEndian();
  9912. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  9913. }
  9914. });
  9915. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  9916. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  9917. PDFJS.PasswordException = sharedUtil.PasswordException;
  9918. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  9919. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  9920. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  9921. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  9922. PDFJS.Util = sharedUtil.Util;
  9923. PDFJS.PageViewport = sharedUtil.PageViewport;
  9924. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  9925. /**
  9926. * The maximum allowed image size in total pixels e.g. width * height. Images
  9927. * above this value will not be drawn. Use -1 for no limit.
  9928. * @var {number}
  9929. */
  9930. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  9931. -1 : PDFJS.maxImageSize);
  9932. /**
  9933. * The url of where the predefined Adobe CMaps are located. Include trailing
  9934. * slash.
  9935. * @var {string}
  9936. */
  9937. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  9938. /**
  9939. * Specifies if CMaps are binary packed.
  9940. * @var {boolean}
  9941. */
  9942. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  9943. /**
  9944. * By default fonts are converted to OpenType fonts and loaded via font face
  9945. * rules. If disabled, the font will be rendered using a built in font
  9946. * renderer that constructs the glyphs with primitive path commands.
  9947. * @var {boolean}
  9948. */
  9949. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  9950. false : PDFJS.disableFontFace);
  9951. /**
  9952. * Path for image resources, mainly for annotation icons. Include trailing
  9953. * slash.
  9954. * @var {string}
  9955. */
  9956. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  9957. '' : PDFJS.imageResourcesPath);
  9958. /**
  9959. * Disable the web worker and run all code on the main thread. This will
  9960. * happen automatically if the browser doesn't support workers or sending
  9961. * typed arrays to workers.
  9962. * @var {boolean}
  9963. */
  9964. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  9965. false : PDFJS.disableWorker);
  9966. /**
  9967. * Path and filename of the worker file. Required when the worker is enabled
  9968. * in development mode. If unspecified in the production build, the worker
  9969. * will be loaded based on the location of the pdf.js file. It is recommended
  9970. * that the workerSrc is set in a custom application to prevent issues caused
  9971. * by third-party frameworks and libraries.
  9972. * @var {string}
  9973. */
  9974. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  9975. /**
  9976. * Disable range request loading of PDF files. When enabled and if the server
  9977. * supports partial content requests then the PDF will be fetched in chunks.
  9978. * Enabled (false) by default.
  9979. * @var {boolean}
  9980. */
  9981. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  9982. false : PDFJS.disableRange);
  9983. /**
  9984. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  9985. * in chunks. This default behavior can be disabled.
  9986. * @var {boolean}
  9987. */
  9988. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  9989. false : PDFJS.disableStream);
  9990. /**
  9991. * Disable pre-fetching of PDF file data. When range requests are enabled
  9992. * PDF.js will automatically keep fetching more data even if it isn't needed
  9993. * to display the current page. This default behavior can be disabled.
  9994. *
  9995. * NOTE: It is also necessary to disable streaming, see above,
  9996. * in order for disabling of pre-fetching to work correctly.
  9997. * @var {boolean}
  9998. */
  9999. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  10000. false : PDFJS.disableAutoFetch);
  10001. /**
  10002. * Enables special hooks for debugging PDF.js.
  10003. * @var {boolean}
  10004. */
  10005. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  10006. /**
  10007. * Enables transfer usage in postMessage for ArrayBuffers.
  10008. * @var {boolean}
  10009. */
  10010. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  10011. true : PDFJS.postMessageTransfers);
  10012. /**
  10013. * Disables URL.createObjectURL usage.
  10014. * @var {boolean}
  10015. */
  10016. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  10017. false : PDFJS.disableCreateObjectURL);
  10018. /**
  10019. * Disables WebGL usage.
  10020. * @var {boolean}
  10021. */
  10022. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  10023. true : PDFJS.disableWebGL);
  10024. /**
  10025. * Specifies the |target| attribute for external links.
  10026. * The constants from PDFJS.LinkTarget should be used:
  10027. * - NONE [default]
  10028. * - SELF
  10029. * - BLANK
  10030. * - PARENT
  10031. * - TOP
  10032. * @var {number}
  10033. */
  10034. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  10035. LinkTarget.NONE : PDFJS.externalLinkTarget);
  10036. /**
  10037. * Specifies the |rel| attribute for external links. Defaults to stripping
  10038. * the referrer.
  10039. * @var {string}
  10040. */
  10041. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  10042. 'noreferrer' : PDFJS.externalLinkRel);
  10043. /**
  10044. * Determines if we can eval strings as JS. Primarily used to improve
  10045. * performance for font rendering.
  10046. * @var {boolean}
  10047. */
  10048. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  10049. true : PDFJS.isEvalSupported);
  10050. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10051. delete PDFJS.openExternalLinksInNewWindow;
  10052. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10053. get: function () {
  10054. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10055. },
  10056. set: function (value) {
  10057. if (value) {
  10058. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  10059. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10060. }
  10061. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10062. warn('PDFJS.externalLinkTarget is already initialized');
  10063. return;
  10064. }
  10065. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10066. },
  10067. enumerable: true,
  10068. configurable: true
  10069. });
  10070. if (savedOpenExternalLinksInNewWindow) {
  10071. /**
  10072. * (Deprecated) Opens external links in a new window if enabled.
  10073. * The default behavior opens external links in the PDF.js window.
  10074. *
  10075. * NOTE: This property has been deprecated, please use
  10076. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10077. * @var {boolean}
  10078. */
  10079. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10080. }
  10081. PDFJS.getDocument = displayAPI.getDocument;
  10082. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10083. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10084. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10085. configurable: true,
  10086. get: function PDFJS_hasCanvasTypedArrays() {
  10087. var value = displayDOMUtils.hasCanvasTypedArrays();
  10088. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10089. }
  10090. });
  10091. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10092. PDFJS.LinkTarget = LinkTarget;
  10093. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10094. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10095. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10096. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10097. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10098. PDFJS.Metadata = displayMetadata.Metadata;
  10099. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10100. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10101. exports.globalScope = globalScope;
  10102. exports.isWorker = isWorker;
  10103. exports.PDFJS = globalScope.PDFJS;
  10104. }));
  10105. }).call(pdfjsLibs);
  10106. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10107. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10108. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10109. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10110. exports.PDFDataRangeTransport =
  10111. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10112. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10113. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10114. exports.AnnotationLayer =
  10115. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10116. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10117. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10118. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10119. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10120. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10121. exports.UnexpectedResponseException =
  10122. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10123. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10124. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10125. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10126. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10127. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10128. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10129. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10130. exports.getFilenameFromUrl =
  10131. pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10132. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10133. }));