2
0

pdf.js 368 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579
  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.6.222';
  30. var pdfjsBuild = 'd714873';
  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 AnnotationFieldFlag = {
  103. READONLY: 0x0000001,
  104. REQUIRED: 0x0000002,
  105. NOEXPORT: 0x0000004,
  106. MULTILINE: 0x0001000,
  107. PASSWORD: 0x0002000,
  108. NOTOGGLETOOFF: 0x0004000,
  109. RADIO: 0x0008000,
  110. PUSHBUTTON: 0x0010000,
  111. COMBO: 0x0020000,
  112. EDIT: 0x0040000,
  113. SORT: 0x0080000,
  114. FILESELECT: 0x0100000,
  115. MULTISELECT: 0x0200000,
  116. DONOTSPELLCHECK: 0x0400000,
  117. DONOTSCROLL: 0x0800000,
  118. COMB: 0x1000000,
  119. RICHTEXT: 0x2000000,
  120. RADIOSINUNISON: 0x2000000,
  121. COMMITONSELCHANGE: 0x4000000,
  122. };
  123. var AnnotationBorderStyleType = {
  124. SOLID: 1,
  125. DASHED: 2,
  126. BEVELED: 3,
  127. INSET: 4,
  128. UNDERLINE: 5
  129. };
  130. var StreamType = {
  131. UNKNOWN: 0,
  132. FLATE: 1,
  133. LZW: 2,
  134. DCT: 3,
  135. JPX: 4,
  136. JBIG: 5,
  137. A85: 6,
  138. AHX: 7,
  139. CCF: 8,
  140. RL: 9
  141. };
  142. var FontType = {
  143. UNKNOWN: 0,
  144. TYPE1: 1,
  145. TYPE1C: 2,
  146. CIDFONTTYPE0: 3,
  147. CIDFONTTYPE0C: 4,
  148. TRUETYPE: 5,
  149. CIDFONTTYPE2: 6,
  150. TYPE3: 7,
  151. OPENTYPE: 8,
  152. TYPE0: 9,
  153. MMTYPE1: 10
  154. };
  155. var VERBOSITY_LEVELS = {
  156. errors: 0,
  157. warnings: 1,
  158. infos: 5
  159. };
  160. // All the possible operations for an operator list.
  161. var OPS = {
  162. // Intentionally start from 1 so it is easy to spot bad operators that will be
  163. // 0's.
  164. dependency: 1,
  165. setLineWidth: 2,
  166. setLineCap: 3,
  167. setLineJoin: 4,
  168. setMiterLimit: 5,
  169. setDash: 6,
  170. setRenderingIntent: 7,
  171. setFlatness: 8,
  172. setGState: 9,
  173. save: 10,
  174. restore: 11,
  175. transform: 12,
  176. moveTo: 13,
  177. lineTo: 14,
  178. curveTo: 15,
  179. curveTo2: 16,
  180. curveTo3: 17,
  181. closePath: 18,
  182. rectangle: 19,
  183. stroke: 20,
  184. closeStroke: 21,
  185. fill: 22,
  186. eoFill: 23,
  187. fillStroke: 24,
  188. eoFillStroke: 25,
  189. closeFillStroke: 26,
  190. closeEOFillStroke: 27,
  191. endPath: 28,
  192. clip: 29,
  193. eoClip: 30,
  194. beginText: 31,
  195. endText: 32,
  196. setCharSpacing: 33,
  197. setWordSpacing: 34,
  198. setHScale: 35,
  199. setLeading: 36,
  200. setFont: 37,
  201. setTextRenderingMode: 38,
  202. setTextRise: 39,
  203. moveText: 40,
  204. setLeadingMoveText: 41,
  205. setTextMatrix: 42,
  206. nextLine: 43,
  207. showText: 44,
  208. showSpacedText: 45,
  209. nextLineShowText: 46,
  210. nextLineSetSpacingShowText: 47,
  211. setCharWidth: 48,
  212. setCharWidthAndBounds: 49,
  213. setStrokeColorSpace: 50,
  214. setFillColorSpace: 51,
  215. setStrokeColor: 52,
  216. setStrokeColorN: 53,
  217. setFillColor: 54,
  218. setFillColorN: 55,
  219. setStrokeGray: 56,
  220. setFillGray: 57,
  221. setStrokeRGBColor: 58,
  222. setFillRGBColor: 59,
  223. setStrokeCMYKColor: 60,
  224. setFillCMYKColor: 61,
  225. shadingFill: 62,
  226. beginInlineImage: 63,
  227. beginImageData: 64,
  228. endInlineImage: 65,
  229. paintXObject: 66,
  230. markPoint: 67,
  231. markPointProps: 68,
  232. beginMarkedContent: 69,
  233. beginMarkedContentProps: 70,
  234. endMarkedContent: 71,
  235. beginCompat: 72,
  236. endCompat: 73,
  237. paintFormXObjectBegin: 74,
  238. paintFormXObjectEnd: 75,
  239. beginGroup: 76,
  240. endGroup: 77,
  241. beginAnnotations: 78,
  242. endAnnotations: 79,
  243. beginAnnotation: 80,
  244. endAnnotation: 81,
  245. paintJpegXObject: 82,
  246. paintImageMaskXObject: 83,
  247. paintImageMaskXObjectGroup: 84,
  248. paintImageXObject: 85,
  249. paintInlineImageXObject: 86,
  250. paintInlineImageXObjectGroup: 87,
  251. paintImageXObjectRepeat: 88,
  252. paintImageMaskXObjectRepeat: 89,
  253. paintSolidColorImageMask: 90,
  254. constructPath: 91
  255. };
  256. var verbosity = VERBOSITY_LEVELS.warnings;
  257. function setVerbosityLevel(level) {
  258. verbosity = level;
  259. }
  260. function getVerbosityLevel() {
  261. return verbosity;
  262. }
  263. // A notice for devs. These are good for things that are helpful to devs, such
  264. // as warning that Workers were disabled, which is important to devs but not
  265. // end users.
  266. function info(msg) {
  267. if (verbosity >= VERBOSITY_LEVELS.infos) {
  268. console.log('Info: ' + msg);
  269. }
  270. }
  271. // Non-fatal warnings.
  272. function warn(msg) {
  273. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  274. console.log('Warning: ' + msg);
  275. }
  276. }
  277. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  278. function deprecated(details) {
  279. console.log('Deprecated API usage: ' + details);
  280. }
  281. // Fatal errors that should trigger the fallback UI and halt execution by
  282. // throwing an exception.
  283. function error(msg) {
  284. if (verbosity >= VERBOSITY_LEVELS.errors) {
  285. console.log('Error: ' + msg);
  286. console.log(backtrace());
  287. }
  288. throw new Error(msg);
  289. }
  290. function backtrace() {
  291. try {
  292. throw new Error();
  293. } catch (e) {
  294. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  295. }
  296. }
  297. function assert(cond, msg) {
  298. if (!cond) {
  299. error(msg);
  300. }
  301. }
  302. var UNSUPPORTED_FEATURES = {
  303. unknown: 'unknown',
  304. forms: 'forms',
  305. javaScript: 'javaScript',
  306. smask: 'smask',
  307. shadingPattern: 'shadingPattern',
  308. font: 'font'
  309. };
  310. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  311. function isSameOrigin(baseUrl, otherUrl) {
  312. try {
  313. var base = new URL(baseUrl);
  314. if (!base.origin || base.origin === 'null') {
  315. return false; // non-HTTP url
  316. }
  317. } catch (e) {
  318. return false;
  319. }
  320. var other = new URL(otherUrl, base);
  321. return base.origin === other.origin;
  322. }
  323. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  324. function isValidUrl(url, allowRelative) {
  325. if (!url || typeof url !== 'string') {
  326. return false;
  327. }
  328. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  329. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  330. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  331. if (!protocol) {
  332. return allowRelative;
  333. }
  334. protocol = protocol[0].toLowerCase();
  335. switch (protocol) {
  336. case 'http':
  337. case 'https':
  338. case 'ftp':
  339. case 'mailto':
  340. case 'tel':
  341. return true;
  342. default:
  343. return false;
  344. }
  345. }
  346. function shadow(obj, prop, value) {
  347. Object.defineProperty(obj, prop, { value: value,
  348. enumerable: true,
  349. configurable: true,
  350. writable: false });
  351. return value;
  352. }
  353. function getLookupTableFactory(initializer) {
  354. var lookup;
  355. return function () {
  356. if (initializer) {
  357. lookup = Object.create(null);
  358. initializer(lookup);
  359. initializer = null;
  360. }
  361. return lookup;
  362. };
  363. }
  364. var PasswordResponses = {
  365. NEED_PASSWORD: 1,
  366. INCORRECT_PASSWORD: 2
  367. };
  368. var PasswordException = (function PasswordExceptionClosure() {
  369. function PasswordException(msg, code) {
  370. this.name = 'PasswordException';
  371. this.message = msg;
  372. this.code = code;
  373. }
  374. PasswordException.prototype = new Error();
  375. PasswordException.constructor = PasswordException;
  376. return PasswordException;
  377. })();
  378. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  379. function UnknownErrorException(msg, details) {
  380. this.name = 'UnknownErrorException';
  381. this.message = msg;
  382. this.details = details;
  383. }
  384. UnknownErrorException.prototype = new Error();
  385. UnknownErrorException.constructor = UnknownErrorException;
  386. return UnknownErrorException;
  387. })();
  388. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  389. function InvalidPDFException(msg) {
  390. this.name = 'InvalidPDFException';
  391. this.message = msg;
  392. }
  393. InvalidPDFException.prototype = new Error();
  394. InvalidPDFException.constructor = InvalidPDFException;
  395. return InvalidPDFException;
  396. })();
  397. var MissingPDFException = (function MissingPDFExceptionClosure() {
  398. function MissingPDFException(msg) {
  399. this.name = 'MissingPDFException';
  400. this.message = msg;
  401. }
  402. MissingPDFException.prototype = new Error();
  403. MissingPDFException.constructor = MissingPDFException;
  404. return MissingPDFException;
  405. })();
  406. var UnexpectedResponseException =
  407. (function UnexpectedResponseExceptionClosure() {
  408. function UnexpectedResponseException(msg, status) {
  409. this.name = 'UnexpectedResponseException';
  410. this.message = msg;
  411. this.status = status;
  412. }
  413. UnexpectedResponseException.prototype = new Error();
  414. UnexpectedResponseException.constructor = UnexpectedResponseException;
  415. return UnexpectedResponseException;
  416. })();
  417. var NotImplementedException = (function NotImplementedExceptionClosure() {
  418. function NotImplementedException(msg) {
  419. this.message = msg;
  420. }
  421. NotImplementedException.prototype = new Error();
  422. NotImplementedException.prototype.name = 'NotImplementedException';
  423. NotImplementedException.constructor = NotImplementedException;
  424. return NotImplementedException;
  425. })();
  426. var MissingDataException = (function MissingDataExceptionClosure() {
  427. function MissingDataException(begin, end) {
  428. this.begin = begin;
  429. this.end = end;
  430. this.message = 'Missing data [' + begin + ', ' + end + ')';
  431. }
  432. MissingDataException.prototype = new Error();
  433. MissingDataException.prototype.name = 'MissingDataException';
  434. MissingDataException.constructor = MissingDataException;
  435. return MissingDataException;
  436. })();
  437. var XRefParseException = (function XRefParseExceptionClosure() {
  438. function XRefParseException(msg) {
  439. this.message = msg;
  440. }
  441. XRefParseException.prototype = new Error();
  442. XRefParseException.prototype.name = 'XRefParseException';
  443. XRefParseException.constructor = XRefParseException;
  444. return XRefParseException;
  445. })();
  446. var NullCharactersRegExp = /\x00/g;
  447. function removeNullCharacters(str) {
  448. if (typeof str !== 'string') {
  449. warn('The argument for removeNullCharacters must be a string.');
  450. return str;
  451. }
  452. return str.replace(NullCharactersRegExp, '');
  453. }
  454. function bytesToString(bytes) {
  455. assert(bytes !== null && typeof bytes === 'object' &&
  456. bytes.length !== undefined, 'Invalid argument for bytesToString');
  457. var length = bytes.length;
  458. var MAX_ARGUMENT_COUNT = 8192;
  459. if (length < MAX_ARGUMENT_COUNT) {
  460. return String.fromCharCode.apply(null, bytes);
  461. }
  462. var strBuf = [];
  463. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  464. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  465. var chunk = bytes.subarray(i, chunkEnd);
  466. strBuf.push(String.fromCharCode.apply(null, chunk));
  467. }
  468. return strBuf.join('');
  469. }
  470. function stringToBytes(str) {
  471. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  472. var length = str.length;
  473. var bytes = new Uint8Array(length);
  474. for (var i = 0; i < length; ++i) {
  475. bytes[i] = str.charCodeAt(i) & 0xFF;
  476. }
  477. return bytes;
  478. }
  479. /**
  480. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  481. * @param {Array|Uint8Array|string} arr
  482. * @returns {number}
  483. */
  484. function arrayByteLength(arr) {
  485. if (arr.length !== undefined) {
  486. return arr.length;
  487. }
  488. assert(arr.byteLength !== undefined);
  489. return arr.byteLength;
  490. }
  491. /**
  492. * Combines array items (arrays) into single Uint8Array object.
  493. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  494. * @returns {Uint8Array}
  495. */
  496. function arraysToBytes(arr) {
  497. // Shortcut: if first and only item is Uint8Array, return it.
  498. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) {
  499. return arr[0];
  500. }
  501. var resultLength = 0;
  502. var i, ii = arr.length;
  503. var item, itemLength ;
  504. for (i = 0; i < ii; i++) {
  505. item = arr[i];
  506. itemLength = arrayByteLength(item);
  507. resultLength += itemLength;
  508. }
  509. var pos = 0;
  510. var data = new Uint8Array(resultLength);
  511. for (i = 0; i < ii; i++) {
  512. item = arr[i];
  513. if (!(item instanceof Uint8Array)) {
  514. if (typeof item === 'string') {
  515. item = stringToBytes(item);
  516. } else {
  517. item = new Uint8Array(item);
  518. }
  519. }
  520. itemLength = item.byteLength;
  521. data.set(item, pos);
  522. pos += itemLength;
  523. }
  524. return data;
  525. }
  526. function string32(value) {
  527. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  528. (value >> 8) & 0xff, value & 0xff);
  529. }
  530. function log2(x) {
  531. var n = 1, i = 0;
  532. while (x > n) {
  533. n <<= 1;
  534. i++;
  535. }
  536. return i;
  537. }
  538. function readInt8(data, start) {
  539. return (data[start] << 24) >> 24;
  540. }
  541. function readUint16(data, offset) {
  542. return (data[offset] << 8) | data[offset + 1];
  543. }
  544. function readUint32(data, offset) {
  545. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  546. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  547. }
  548. // Lazy test the endianness of the platform
  549. // NOTE: This will be 'true' for simulated TypedArrays
  550. function isLittleEndian() {
  551. var buffer8 = new Uint8Array(2);
  552. buffer8[0] = 1;
  553. var buffer16 = new Uint16Array(buffer8.buffer);
  554. return (buffer16[0] === 1);
  555. }
  556. // Checks if it's possible to eval JS expressions.
  557. function isEvalSupported() {
  558. try {
  559. /* jshint evil: true */
  560. new Function('');
  561. return true;
  562. } catch (e) {
  563. return false;
  564. }
  565. }
  566. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  567. function Uint32ArrayView(buffer, length) {
  568. this.buffer = buffer;
  569. this.byteLength = buffer.length;
  570. this.length = length === undefined ? (this.byteLength >> 2) : length;
  571. ensureUint32ArrayViewProps(this.length);
  572. }
  573. Uint32ArrayView.prototype = Object.create(null);
  574. var uint32ArrayViewSetters = 0;
  575. function createUint32ArrayProp(index) {
  576. return {
  577. get: function () {
  578. var buffer = this.buffer, offset = index << 2;
  579. return (buffer[offset] | (buffer[offset + 1] << 8) |
  580. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  581. },
  582. set: function (value) {
  583. var buffer = this.buffer, offset = index << 2;
  584. buffer[offset] = value & 255;
  585. buffer[offset + 1] = (value >> 8) & 255;
  586. buffer[offset + 2] = (value >> 16) & 255;
  587. buffer[offset + 3] = (value >>> 24) & 255;
  588. }
  589. };
  590. }
  591. function ensureUint32ArrayViewProps(length) {
  592. while (uint32ArrayViewSetters < length) {
  593. Object.defineProperty(Uint32ArrayView.prototype,
  594. uint32ArrayViewSetters,
  595. createUint32ArrayProp(uint32ArrayViewSetters));
  596. uint32ArrayViewSetters++;
  597. }
  598. }
  599. return Uint32ArrayView;
  600. })();
  601. exports.Uint32ArrayView = Uint32ArrayView;
  602. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  603. var Util = (function UtilClosure() {
  604. function Util() {}
  605. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  606. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  607. // creating many intermediate strings.
  608. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  609. rgbBuf[1] = r;
  610. rgbBuf[3] = g;
  611. rgbBuf[5] = b;
  612. return rgbBuf.join('');
  613. };
  614. // Concatenates two transformation matrices together and returns the result.
  615. Util.transform = function Util_transform(m1, m2) {
  616. return [
  617. m1[0] * m2[0] + m1[2] * m2[1],
  618. m1[1] * m2[0] + m1[3] * m2[1],
  619. m1[0] * m2[2] + m1[2] * m2[3],
  620. m1[1] * m2[2] + m1[3] * m2[3],
  621. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  622. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  623. ];
  624. };
  625. // For 2d affine transforms
  626. Util.applyTransform = function Util_applyTransform(p, m) {
  627. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  628. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  629. return [xt, yt];
  630. };
  631. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  632. var d = m[0] * m[3] - m[1] * m[2];
  633. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  634. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  635. return [xt, yt];
  636. };
  637. // Applies the transform to the rectangle and finds the minimum axially
  638. // aligned bounding box.
  639. Util.getAxialAlignedBoundingBox =
  640. function Util_getAxialAlignedBoundingBox(r, m) {
  641. var p1 = Util.applyTransform(r, m);
  642. var p2 = Util.applyTransform(r.slice(2, 4), m);
  643. var p3 = Util.applyTransform([r[0], r[3]], m);
  644. var p4 = Util.applyTransform([r[2], r[1]], m);
  645. return [
  646. Math.min(p1[0], p2[0], p3[0], p4[0]),
  647. Math.min(p1[1], p2[1], p3[1], p4[1]),
  648. Math.max(p1[0], p2[0], p3[0], p4[0]),
  649. Math.max(p1[1], p2[1], p3[1], p4[1])
  650. ];
  651. };
  652. Util.inverseTransform = function Util_inverseTransform(m) {
  653. var d = m[0] * m[3] - m[1] * m[2];
  654. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  655. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  656. };
  657. // Apply a generic 3d matrix M on a 3-vector v:
  658. // | a b c | | X |
  659. // | d e f | x | Y |
  660. // | g h i | | Z |
  661. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  662. // with v as [X,Y,Z]
  663. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  664. return [
  665. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  666. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  667. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  668. ];
  669. };
  670. // This calculation uses Singular Value Decomposition.
  671. // The SVD can be represented with formula A = USV. We are interested in the
  672. // matrix S here because it represents the scale values.
  673. Util.singularValueDecompose2dScale =
  674. function Util_singularValueDecompose2dScale(m) {
  675. var transpose = [m[0], m[2], m[1], m[3]];
  676. // Multiply matrix m with its transpose.
  677. var a = m[0] * transpose[0] + m[1] * transpose[2];
  678. var b = m[0] * transpose[1] + m[1] * transpose[3];
  679. var c = m[2] * transpose[0] + m[3] * transpose[2];
  680. var d = m[2] * transpose[1] + m[3] * transpose[3];
  681. // Solve the second degree polynomial to get roots.
  682. var first = (a + d) / 2;
  683. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  684. var sx = first + second || 1;
  685. var sy = first - second || 1;
  686. // Scale values are the square roots of the eigenvalues.
  687. return [Math.sqrt(sx), Math.sqrt(sy)];
  688. };
  689. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  690. // For coordinate systems whose origin lies in the bottom-left, this
  691. // means normalization to (BL,TR) ordering. For systems with origin in the
  692. // top-left, this means (TL,BR) ordering.
  693. Util.normalizeRect = function Util_normalizeRect(rect) {
  694. var r = rect.slice(0); // clone rect
  695. if (rect[0] > rect[2]) {
  696. r[0] = rect[2];
  697. r[2] = rect[0];
  698. }
  699. if (rect[1] > rect[3]) {
  700. r[1] = rect[3];
  701. r[3] = rect[1];
  702. }
  703. return r;
  704. };
  705. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  706. // intersection of rect1 and rect2. If no intersection, returns 'false'
  707. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  708. Util.intersect = function Util_intersect(rect1, rect2) {
  709. function compare(a, b) {
  710. return a - b;
  711. }
  712. // Order points along the axes
  713. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  714. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  715. result = [];
  716. rect1 = Util.normalizeRect(rect1);
  717. rect2 = Util.normalizeRect(rect2);
  718. // X: first and second points belong to different rectangles?
  719. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  720. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  721. // Intersection must be between second and third points
  722. result[0] = orderedX[1];
  723. result[2] = orderedX[2];
  724. } else {
  725. return false;
  726. }
  727. // Y: first and second points belong to different rectangles?
  728. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  729. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  730. // Intersection must be between second and third points
  731. result[1] = orderedY[1];
  732. result[3] = orderedY[2];
  733. } else {
  734. return false;
  735. }
  736. return result;
  737. };
  738. Util.sign = function Util_sign(num) {
  739. return num < 0 ? -1 : 1;
  740. };
  741. var ROMAN_NUMBER_MAP = [
  742. '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  743. '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  744. '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
  745. ];
  746. /**
  747. * Converts positive integers to (upper case) Roman numerals.
  748. * @param {integer} number - The number that should be converted.
  749. * @param {boolean} lowerCase - Indicates if the result should be converted
  750. * to lower case letters. The default is false.
  751. * @return {string} The resulting Roman number.
  752. */
  753. Util.toRoman = function Util_toRoman(number, lowerCase) {
  754. assert(isInt(number) && number > 0,
  755. 'The number should be a positive integer.');
  756. var pos, romanBuf = [];
  757. // Thousands
  758. while (number >= 1000) {
  759. number -= 1000;
  760. romanBuf.push('M');
  761. }
  762. // Hundreds
  763. pos = (number / 100) | 0;
  764. number %= 100;
  765. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  766. // Tens
  767. pos = (number / 10) | 0;
  768. number %= 10;
  769. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  770. // Ones
  771. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  772. var romanStr = romanBuf.join('');
  773. return (lowerCase ? romanStr.toLowerCase() : romanStr);
  774. };
  775. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  776. Array.prototype.push.apply(arr1, arr2);
  777. };
  778. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  779. Array.prototype.unshift.apply(arr1, arr2);
  780. };
  781. Util.extendObj = function extendObj(obj1, obj2) {
  782. for (var key in obj2) {
  783. obj1[key] = obj2[key];
  784. }
  785. };
  786. Util.getInheritableProperty =
  787. function Util_getInheritableProperty(dict, name, getArray) {
  788. while (dict && !dict.has(name)) {
  789. dict = dict.get('Parent');
  790. }
  791. if (!dict) {
  792. return null;
  793. }
  794. return getArray ? dict.getArray(name) : dict.get(name);
  795. };
  796. Util.inherit = function Util_inherit(sub, base, prototype) {
  797. sub.prototype = Object.create(base.prototype);
  798. sub.prototype.constructor = sub;
  799. for (var prop in prototype) {
  800. sub.prototype[prop] = prototype[prop];
  801. }
  802. };
  803. Util.loadScript = function Util_loadScript(src, callback) {
  804. var script = document.createElement('script');
  805. var loaded = false;
  806. script.setAttribute('src', src);
  807. if (callback) {
  808. script.onload = function() {
  809. if (!loaded) {
  810. callback();
  811. }
  812. loaded = true;
  813. };
  814. }
  815. document.getElementsByTagName('head')[0].appendChild(script);
  816. };
  817. return Util;
  818. })();
  819. /**
  820. * PDF page viewport created based on scale, rotation and offset.
  821. * @class
  822. * @alias PageViewport
  823. */
  824. var PageViewport = (function PageViewportClosure() {
  825. /**
  826. * @constructor
  827. * @private
  828. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  829. * @param scale {number} scale of the viewport.
  830. * @param rotation {number} rotations of the viewport in degrees.
  831. * @param offsetX {number} offset X
  832. * @param offsetY {number} offset Y
  833. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  834. */
  835. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  836. this.viewBox = viewBox;
  837. this.scale = scale;
  838. this.rotation = rotation;
  839. this.offsetX = offsetX;
  840. this.offsetY = offsetY;
  841. // creating transform to convert pdf coordinate system to the normal
  842. // canvas like coordinates taking in account scale and rotation
  843. var centerX = (viewBox[2] + viewBox[0]) / 2;
  844. var centerY = (viewBox[3] + viewBox[1]) / 2;
  845. var rotateA, rotateB, rotateC, rotateD;
  846. rotation = rotation % 360;
  847. rotation = rotation < 0 ? rotation + 360 : rotation;
  848. switch (rotation) {
  849. case 180:
  850. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  851. break;
  852. case 90:
  853. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  854. break;
  855. case 270:
  856. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  857. break;
  858. //case 0:
  859. default:
  860. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  861. break;
  862. }
  863. if (dontFlip) {
  864. rotateC = -rotateC; rotateD = -rotateD;
  865. }
  866. var offsetCanvasX, offsetCanvasY;
  867. var width, height;
  868. if (rotateA === 0) {
  869. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  870. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  871. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  872. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  873. } else {
  874. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  875. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  876. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  877. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  878. }
  879. // creating transform for the following operations:
  880. // translate(-centerX, -centerY), rotate and flip vertically,
  881. // scale, and translate(offsetCanvasX, offsetCanvasY)
  882. this.transform = [
  883. rotateA * scale,
  884. rotateB * scale,
  885. rotateC * scale,
  886. rotateD * scale,
  887. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  888. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  889. ];
  890. this.width = width;
  891. this.height = height;
  892. this.fontScale = scale;
  893. }
  894. PageViewport.prototype = /** @lends PageViewport.prototype */ {
  895. /**
  896. * Clones viewport with additional properties.
  897. * @param args {Object} (optional) If specified, may contain the 'scale' or
  898. * 'rotation' properties to override the corresponding properties in
  899. * the cloned viewport.
  900. * @returns {PageViewport} Cloned viewport.
  901. */
  902. clone: function PageViewPort_clone(args) {
  903. args = args || {};
  904. var scale = 'scale' in args ? args.scale : this.scale;
  905. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  906. return new PageViewport(this.viewBox.slice(), scale, rotation,
  907. this.offsetX, this.offsetY, args.dontFlip);
  908. },
  909. /**
  910. * Converts PDF point to the viewport coordinates. For examples, useful for
  911. * converting PDF location into canvas pixel coordinates.
  912. * @param x {number} X coordinate.
  913. * @param y {number} Y coordinate.
  914. * @returns {Object} Object that contains 'x' and 'y' properties of the
  915. * point in the viewport coordinate space.
  916. * @see {@link convertToPdfPoint}
  917. * @see {@link convertToViewportRectangle}
  918. */
  919. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  920. return Util.applyTransform([x, y], this.transform);
  921. },
  922. /**
  923. * Converts PDF rectangle to the viewport coordinates.
  924. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  925. * @returns {Array} Contains corresponding coordinates of the rectangle
  926. * in the viewport coordinate space.
  927. * @see {@link convertToViewportPoint}
  928. */
  929. convertToViewportRectangle:
  930. function PageViewport_convertToViewportRectangle(rect) {
  931. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  932. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  933. return [tl[0], tl[1], br[0], br[1]];
  934. },
  935. /**
  936. * Converts viewport coordinates to the PDF location. For examples, useful
  937. * for converting canvas pixel location into PDF one.
  938. * @param x {number} X coordinate.
  939. * @param y {number} Y coordinate.
  940. * @returns {Object} Object that contains 'x' and 'y' properties of the
  941. * point in the PDF coordinate space.
  942. * @see {@link convertToViewportPoint}
  943. */
  944. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  945. return Util.applyInverseTransform([x, y], this.transform);
  946. }
  947. };
  948. return PageViewport;
  949. })();
  950. var PDFStringTranslateTable = [
  951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  952. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  953. 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,
  954. 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,
  955. 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,
  956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  957. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  958. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  959. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  960. ];
  961. function stringToPDFString(str) {
  962. var i, n = str.length, strBuf = [];
  963. if (str[0] === '\xFE' && str[1] === '\xFF') {
  964. // UTF16BE BOM
  965. for (i = 2; i < n; i += 2) {
  966. strBuf.push(String.fromCharCode(
  967. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  968. }
  969. } else {
  970. for (i = 0; i < n; ++i) {
  971. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  972. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  973. }
  974. }
  975. return strBuf.join('');
  976. }
  977. function stringToUTF8String(str) {
  978. return decodeURIComponent(escape(str));
  979. }
  980. function utf8StringToString(str) {
  981. return unescape(encodeURIComponent(str));
  982. }
  983. function isEmptyObj(obj) {
  984. for (var key in obj) {
  985. return false;
  986. }
  987. return true;
  988. }
  989. function isBool(v) {
  990. return typeof v === 'boolean';
  991. }
  992. function isInt(v) {
  993. return typeof v === 'number' && ((v | 0) === v);
  994. }
  995. function isNum(v) {
  996. return typeof v === 'number';
  997. }
  998. function isString(v) {
  999. return typeof v === 'string';
  1000. }
  1001. function isArray(v) {
  1002. return v instanceof Array;
  1003. }
  1004. function isArrayBuffer(v) {
  1005. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1006. }
  1007. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1008. function isSpace(ch) {
  1009. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  1010. }
  1011. /**
  1012. * Promise Capability object.
  1013. *
  1014. * @typedef {Object} PromiseCapability
  1015. * @property {Promise} promise - A promise object.
  1016. * @property {function} resolve - Fulfills the promise.
  1017. * @property {function} reject - Rejects the promise.
  1018. */
  1019. /**
  1020. * Creates a promise capability object.
  1021. * @alias createPromiseCapability
  1022. *
  1023. * @return {PromiseCapability} A capability object contains:
  1024. * - a Promise, resolve and reject methods.
  1025. */
  1026. function createPromiseCapability() {
  1027. var capability = {};
  1028. capability.promise = new Promise(function (resolve, reject) {
  1029. capability.resolve = resolve;
  1030. capability.reject = reject;
  1031. });
  1032. return capability;
  1033. }
  1034. /**
  1035. * Polyfill for Promises:
  1036. * The following promise implementation tries to generally implement the
  1037. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1038. * - There currently isn't a separate deferred and promise object.
  1039. * - Unhandled rejections eventually show an error if they aren't handled.
  1040. *
  1041. * Based off of the work in:
  1042. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1043. */
  1044. (function PromiseClosure() {
  1045. if (globalScope.Promise) {
  1046. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1047. if (typeof globalScope.Promise.all !== 'function') {
  1048. globalScope.Promise.all = function (iterable) {
  1049. var count = 0, results = [], resolve, reject;
  1050. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1051. resolve = resolve_;
  1052. reject = reject_;
  1053. });
  1054. iterable.forEach(function (p, i) {
  1055. count++;
  1056. p.then(function (result) {
  1057. results[i] = result;
  1058. count--;
  1059. if (count === 0) {
  1060. resolve(results);
  1061. }
  1062. }, reject);
  1063. });
  1064. if (count === 0) {
  1065. resolve(results);
  1066. }
  1067. return promise;
  1068. };
  1069. }
  1070. if (typeof globalScope.Promise.resolve !== 'function') {
  1071. globalScope.Promise.resolve = function (value) {
  1072. return new globalScope.Promise(function (resolve) { resolve(value); });
  1073. };
  1074. }
  1075. if (typeof globalScope.Promise.reject !== 'function') {
  1076. globalScope.Promise.reject = function (reason) {
  1077. return new globalScope.Promise(function (resolve, reject) {
  1078. reject(reason);
  1079. });
  1080. };
  1081. }
  1082. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1083. globalScope.Promise.prototype.catch = function (onReject) {
  1084. return globalScope.Promise.prototype.then(undefined, onReject);
  1085. };
  1086. }
  1087. return;
  1088. }
  1089. var STATUS_PENDING = 0;
  1090. var STATUS_RESOLVED = 1;
  1091. var STATUS_REJECTED = 2;
  1092. // In an attempt to avoid silent exceptions, unhandled rejections are
  1093. // tracked and if they aren't handled in a certain amount of time an
  1094. // error is logged.
  1095. var REJECTION_TIMEOUT = 500;
  1096. var HandlerManager = {
  1097. handlers: [],
  1098. running: false,
  1099. unhandledRejections: [],
  1100. pendingRejectionCheck: false,
  1101. scheduleHandlers: function scheduleHandlers(promise) {
  1102. if (promise._status === STATUS_PENDING) {
  1103. return;
  1104. }
  1105. this.handlers = this.handlers.concat(promise._handlers);
  1106. promise._handlers = [];
  1107. if (this.running) {
  1108. return;
  1109. }
  1110. this.running = true;
  1111. setTimeout(this.runHandlers.bind(this), 0);
  1112. },
  1113. runHandlers: function runHandlers() {
  1114. var RUN_TIMEOUT = 1; // ms
  1115. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1116. while (this.handlers.length > 0) {
  1117. var handler = this.handlers.shift();
  1118. var nextStatus = handler.thisPromise._status;
  1119. var nextValue = handler.thisPromise._value;
  1120. try {
  1121. if (nextStatus === STATUS_RESOLVED) {
  1122. if (typeof handler.onResolve === 'function') {
  1123. nextValue = handler.onResolve(nextValue);
  1124. }
  1125. } else if (typeof handler.onReject === 'function') {
  1126. nextValue = handler.onReject(nextValue);
  1127. nextStatus = STATUS_RESOLVED;
  1128. if (handler.thisPromise._unhandledRejection) {
  1129. this.removeUnhandeledRejection(handler.thisPromise);
  1130. }
  1131. }
  1132. } catch (ex) {
  1133. nextStatus = STATUS_REJECTED;
  1134. nextValue = ex;
  1135. }
  1136. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1137. if (Date.now() >= timeoutAt) {
  1138. break;
  1139. }
  1140. }
  1141. if (this.handlers.length > 0) {
  1142. setTimeout(this.runHandlers.bind(this), 0);
  1143. return;
  1144. }
  1145. this.running = false;
  1146. },
  1147. addUnhandledRejection: function addUnhandledRejection(promise) {
  1148. this.unhandledRejections.push({
  1149. promise: promise,
  1150. time: Date.now()
  1151. });
  1152. this.scheduleRejectionCheck();
  1153. },
  1154. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1155. promise._unhandledRejection = false;
  1156. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1157. if (this.unhandledRejections[i].promise === promise) {
  1158. this.unhandledRejections.splice(i);
  1159. i--;
  1160. }
  1161. }
  1162. },
  1163. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1164. if (this.pendingRejectionCheck) {
  1165. return;
  1166. }
  1167. this.pendingRejectionCheck = true;
  1168. setTimeout(function rejectionCheck() {
  1169. this.pendingRejectionCheck = false;
  1170. var now = Date.now();
  1171. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1172. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1173. var unhandled = this.unhandledRejections[i].promise._value;
  1174. var msg = 'Unhandled rejection: ' + unhandled;
  1175. if (unhandled.stack) {
  1176. msg += '\n' + unhandled.stack;
  1177. }
  1178. warn(msg);
  1179. this.unhandledRejections.splice(i);
  1180. i--;
  1181. }
  1182. }
  1183. if (this.unhandledRejections.length) {
  1184. this.scheduleRejectionCheck();
  1185. }
  1186. }.bind(this), REJECTION_TIMEOUT);
  1187. }
  1188. };
  1189. function Promise(resolver) {
  1190. this._status = STATUS_PENDING;
  1191. this._handlers = [];
  1192. try {
  1193. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1194. } catch (e) {
  1195. this._reject(e);
  1196. }
  1197. }
  1198. /**
  1199. * Builds a promise that is resolved when all the passed in promises are
  1200. * resolved.
  1201. * @param {array} promises array of data and/or promises to wait for.
  1202. * @return {Promise} New dependent promise.
  1203. */
  1204. Promise.all = function Promise_all(promises) {
  1205. var resolveAll, rejectAll;
  1206. var deferred = new Promise(function (resolve, reject) {
  1207. resolveAll = resolve;
  1208. rejectAll = reject;
  1209. });
  1210. var unresolved = promises.length;
  1211. var results = [];
  1212. if (unresolved === 0) {
  1213. resolveAll(results);
  1214. return deferred;
  1215. }
  1216. function reject(reason) {
  1217. if (deferred._status === STATUS_REJECTED) {
  1218. return;
  1219. }
  1220. results = [];
  1221. rejectAll(reason);
  1222. }
  1223. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1224. var promise = promises[i];
  1225. var resolve = (function(i) {
  1226. return function(value) {
  1227. if (deferred._status === STATUS_REJECTED) {
  1228. return;
  1229. }
  1230. results[i] = value;
  1231. unresolved--;
  1232. if (unresolved === 0) {
  1233. resolveAll(results);
  1234. }
  1235. };
  1236. })(i);
  1237. if (Promise.isPromise(promise)) {
  1238. promise.then(resolve, reject);
  1239. } else {
  1240. resolve(promise);
  1241. }
  1242. }
  1243. return deferred;
  1244. };
  1245. /**
  1246. * Checks if the value is likely a promise (has a 'then' function).
  1247. * @return {boolean} true if value is thenable
  1248. */
  1249. Promise.isPromise = function Promise_isPromise(value) {
  1250. return value && typeof value.then === 'function';
  1251. };
  1252. /**
  1253. * Creates resolved promise
  1254. * @param value resolve value
  1255. * @returns {Promise}
  1256. */
  1257. Promise.resolve = function Promise_resolve(value) {
  1258. return new Promise(function (resolve) { resolve(value); });
  1259. };
  1260. /**
  1261. * Creates rejected promise
  1262. * @param reason rejection value
  1263. * @returns {Promise}
  1264. */
  1265. Promise.reject = function Promise_reject(reason) {
  1266. return new Promise(function (resolve, reject) { reject(reason); });
  1267. };
  1268. Promise.prototype = {
  1269. _status: null,
  1270. _value: null,
  1271. _handlers: null,
  1272. _unhandledRejection: null,
  1273. _updateStatus: function Promise__updateStatus(status, value) {
  1274. if (this._status === STATUS_RESOLVED ||
  1275. this._status === STATUS_REJECTED) {
  1276. return;
  1277. }
  1278. if (status === STATUS_RESOLVED &&
  1279. Promise.isPromise(value)) {
  1280. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1281. this._updateStatus.bind(this, STATUS_REJECTED));
  1282. return;
  1283. }
  1284. this._status = status;
  1285. this._value = value;
  1286. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1287. this._unhandledRejection = true;
  1288. HandlerManager.addUnhandledRejection(this);
  1289. }
  1290. HandlerManager.scheduleHandlers(this);
  1291. },
  1292. _resolve: function Promise_resolve(value) {
  1293. this._updateStatus(STATUS_RESOLVED, value);
  1294. },
  1295. _reject: function Promise_reject(reason) {
  1296. this._updateStatus(STATUS_REJECTED, reason);
  1297. },
  1298. then: function Promise_then(onResolve, onReject) {
  1299. var nextPromise = new Promise(function (resolve, reject) {
  1300. this.resolve = resolve;
  1301. this.reject = reject;
  1302. });
  1303. this._handlers.push({
  1304. thisPromise: this,
  1305. onResolve: onResolve,
  1306. onReject: onReject,
  1307. nextPromise: nextPromise
  1308. });
  1309. HandlerManager.scheduleHandlers(this);
  1310. return nextPromise;
  1311. },
  1312. catch: function Promise_catch(onReject) {
  1313. return this.then(undefined, onReject);
  1314. }
  1315. };
  1316. globalScope.Promise = Promise;
  1317. })();
  1318. (function WeakMapClosure() {
  1319. if (globalScope.WeakMap) {
  1320. return;
  1321. }
  1322. var id = 0;
  1323. function WeakMap() {
  1324. this.id = '$weakmap' + (id++);
  1325. }
  1326. WeakMap.prototype = {
  1327. has: function(obj) {
  1328. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1329. },
  1330. get: function(obj, defaultValue) {
  1331. return this.has(obj) ? obj[this.id] : defaultValue;
  1332. },
  1333. set: function(obj, value) {
  1334. Object.defineProperty(obj, this.id, {
  1335. value: value,
  1336. enumerable: false,
  1337. configurable: true
  1338. });
  1339. },
  1340. delete: function(obj) {
  1341. delete obj[this.id];
  1342. }
  1343. };
  1344. globalScope.WeakMap = WeakMap;
  1345. })();
  1346. var StatTimer = (function StatTimerClosure() {
  1347. function rpad(str, pad, length) {
  1348. while (str.length < length) {
  1349. str += pad;
  1350. }
  1351. return str;
  1352. }
  1353. function StatTimer() {
  1354. this.started = Object.create(null);
  1355. this.times = [];
  1356. this.enabled = true;
  1357. }
  1358. StatTimer.prototype = {
  1359. time: function StatTimer_time(name) {
  1360. if (!this.enabled) {
  1361. return;
  1362. }
  1363. if (name in this.started) {
  1364. warn('Timer is already running for ' + name);
  1365. }
  1366. this.started[name] = Date.now();
  1367. },
  1368. timeEnd: function StatTimer_timeEnd(name) {
  1369. if (!this.enabled) {
  1370. return;
  1371. }
  1372. if (!(name in this.started)) {
  1373. warn('Timer has not been started for ' + name);
  1374. }
  1375. this.times.push({
  1376. 'name': name,
  1377. 'start': this.started[name],
  1378. 'end': Date.now()
  1379. });
  1380. // Remove timer from started so it can be called again.
  1381. delete this.started[name];
  1382. },
  1383. toString: function StatTimer_toString() {
  1384. var i, ii;
  1385. var times = this.times;
  1386. var out = '';
  1387. // Find the longest name for padding purposes.
  1388. var longest = 0;
  1389. for (i = 0, ii = times.length; i < ii; ++i) {
  1390. var name = times[i]['name'];
  1391. if (name.length > longest) {
  1392. longest = name.length;
  1393. }
  1394. }
  1395. for (i = 0, ii = times.length; i < ii; ++i) {
  1396. var span = times[i];
  1397. var duration = span.end - span.start;
  1398. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1399. }
  1400. return out;
  1401. }
  1402. };
  1403. return StatTimer;
  1404. })();
  1405. var createBlob = function createBlob(data, contentType) {
  1406. if (typeof Blob !== 'undefined') {
  1407. return new Blob([data], { type: contentType });
  1408. }
  1409. warn('The "Blob" constructor is not supported.');
  1410. };
  1411. var createObjectURL = (function createObjectURLClosure() {
  1412. // Blob/createObjectURL is not available, falling back to data schema.
  1413. var digits =
  1414. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1415. return function createObjectURL(data, contentType, forceDataSchema) {
  1416. if (!forceDataSchema &&
  1417. typeof URL !== 'undefined' && URL.createObjectURL) {
  1418. var blob = createBlob(data, contentType);
  1419. return URL.createObjectURL(blob);
  1420. }
  1421. var buffer = 'data:' + contentType + ';base64,';
  1422. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1423. var b1 = data[i] & 0xFF;
  1424. var b2 = data[i + 1] & 0xFF;
  1425. var b3 = data[i + 2] & 0xFF;
  1426. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1427. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1428. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1429. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1430. }
  1431. return buffer;
  1432. };
  1433. })();
  1434. function MessageHandler(sourceName, targetName, comObj) {
  1435. this.sourceName = sourceName;
  1436. this.targetName = targetName;
  1437. this.comObj = comObj;
  1438. this.callbackIndex = 1;
  1439. this.postMessageTransfers = true;
  1440. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1441. var ah = this.actionHandler = Object.create(null);
  1442. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1443. var data = event.data;
  1444. if (data.targetName !== this.sourceName) {
  1445. return;
  1446. }
  1447. if (data.isReply) {
  1448. var callbackId = data.callbackId;
  1449. if (data.callbackId in callbacksCapabilities) {
  1450. var callback = callbacksCapabilities[callbackId];
  1451. delete callbacksCapabilities[callbackId];
  1452. if ('error' in data) {
  1453. callback.reject(data.error);
  1454. } else {
  1455. callback.resolve(data.data);
  1456. }
  1457. } else {
  1458. error('Cannot resolve callback ' + callbackId);
  1459. }
  1460. } else if (data.action in ah) {
  1461. var action = ah[data.action];
  1462. if (data.callbackId) {
  1463. var sourceName = this.sourceName;
  1464. var targetName = data.sourceName;
  1465. Promise.resolve().then(function () {
  1466. return action[0].call(action[1], data.data);
  1467. }).then(function (result) {
  1468. comObj.postMessage({
  1469. sourceName: sourceName,
  1470. targetName: targetName,
  1471. isReply: true,
  1472. callbackId: data.callbackId,
  1473. data: result
  1474. });
  1475. }, function (reason) {
  1476. if (reason instanceof Error) {
  1477. // Serialize error to avoid "DataCloneError"
  1478. reason = reason + '';
  1479. }
  1480. comObj.postMessage({
  1481. sourceName: sourceName,
  1482. targetName: targetName,
  1483. isReply: true,
  1484. callbackId: data.callbackId,
  1485. error: reason
  1486. });
  1487. });
  1488. } else {
  1489. action[0].call(action[1], data.data);
  1490. }
  1491. } else {
  1492. error('Unknown action from worker: ' + data.action);
  1493. }
  1494. }.bind(this);
  1495. comObj.addEventListener('message', this._onComObjOnMessage);
  1496. }
  1497. MessageHandler.prototype = {
  1498. on: function messageHandlerOn(actionName, handler, scope) {
  1499. var ah = this.actionHandler;
  1500. if (ah[actionName]) {
  1501. error('There is already an actionName called "' + actionName + '"');
  1502. }
  1503. ah[actionName] = [handler, scope];
  1504. },
  1505. /**
  1506. * Sends a message to the comObj to invoke the action with the supplied data.
  1507. * @param {String} actionName Action to call.
  1508. * @param {JSON} data JSON data to send.
  1509. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1510. */
  1511. send: function messageHandlerSend(actionName, data, transfers) {
  1512. var message = {
  1513. sourceName: this.sourceName,
  1514. targetName: this.targetName,
  1515. action: actionName,
  1516. data: data
  1517. };
  1518. this.postMessage(message, transfers);
  1519. },
  1520. /**
  1521. * Sends a message to the comObj to invoke the action with the supplied data.
  1522. * Expects that other side will callback with the response.
  1523. * @param {String} actionName Action to call.
  1524. * @param {JSON} data JSON data to send.
  1525. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1526. * @returns {Promise} Promise to be resolved with response data.
  1527. */
  1528. sendWithPromise:
  1529. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1530. var callbackId = this.callbackIndex++;
  1531. var message = {
  1532. sourceName: this.sourceName,
  1533. targetName: this.targetName,
  1534. action: actionName,
  1535. data: data,
  1536. callbackId: callbackId
  1537. };
  1538. var capability = createPromiseCapability();
  1539. this.callbacksCapabilities[callbackId] = capability;
  1540. try {
  1541. this.postMessage(message, transfers);
  1542. } catch (e) {
  1543. capability.reject(e);
  1544. }
  1545. return capability.promise;
  1546. },
  1547. /**
  1548. * Sends raw message to the comObj.
  1549. * @private
  1550. * @param message {Object} Raw message.
  1551. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1552. */
  1553. postMessage: function (message, transfers) {
  1554. if (transfers && this.postMessageTransfers) {
  1555. this.comObj.postMessage(message, transfers);
  1556. } else {
  1557. this.comObj.postMessage(message);
  1558. }
  1559. },
  1560. destroy: function () {
  1561. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1562. }
  1563. };
  1564. function loadJpegStream(id, imageUrl, objs) {
  1565. var img = new Image();
  1566. img.onload = (function loadJpegStream_onloadClosure() {
  1567. objs.resolve(id, img);
  1568. });
  1569. img.onerror = (function loadJpegStream_onerrorClosure() {
  1570. objs.resolve(id, null);
  1571. warn('Error during JPEG image loading');
  1572. });
  1573. img.src = imageUrl;
  1574. }
  1575. // Polyfill from https://github.com/Polymer/URL
  1576. /* Any copyright is dedicated to the Public Domain.
  1577. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1578. (function checkURLConstructor(scope) {
  1579. // feature detect for URL constructor
  1580. var hasWorkingUrl = false;
  1581. try {
  1582. if (typeof URL === 'function' &&
  1583. typeof URL.prototype === 'object' &&
  1584. ('origin' in URL.prototype)) {
  1585. var u = new URL('b', 'http://a');
  1586. u.pathname = 'c%20d';
  1587. hasWorkingUrl = u.href === 'http://a/c%20d';
  1588. }
  1589. } catch(e) { }
  1590. if (hasWorkingUrl) {
  1591. return;
  1592. }
  1593. var relative = Object.create(null);
  1594. relative['ftp'] = 21;
  1595. relative['file'] = 0;
  1596. relative['gopher'] = 70;
  1597. relative['http'] = 80;
  1598. relative['https'] = 443;
  1599. relative['ws'] = 80;
  1600. relative['wss'] = 443;
  1601. var relativePathDotMapping = Object.create(null);
  1602. relativePathDotMapping['%2e'] = '.';
  1603. relativePathDotMapping['.%2e'] = '..';
  1604. relativePathDotMapping['%2e.'] = '..';
  1605. relativePathDotMapping['%2e%2e'] = '..';
  1606. function isRelativeScheme(scheme) {
  1607. return relative[scheme] !== undefined;
  1608. }
  1609. function invalid() {
  1610. clear.call(this);
  1611. this._isInvalid = true;
  1612. }
  1613. function IDNAToASCII(h) {
  1614. if ('' === h) {
  1615. invalid.call(this);
  1616. }
  1617. // XXX
  1618. return h.toLowerCase();
  1619. }
  1620. function percentEscape(c) {
  1621. var unicode = c.charCodeAt(0);
  1622. if (unicode > 0x20 &&
  1623. unicode < 0x7F &&
  1624. // " # < > ? `
  1625. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1
  1626. ) {
  1627. return c;
  1628. }
  1629. return encodeURIComponent(c);
  1630. }
  1631. function percentEscapeQuery(c) {
  1632. // XXX This actually needs to encode c using encoding and then
  1633. // convert the bytes one-by-one.
  1634. var unicode = c.charCodeAt(0);
  1635. if (unicode > 0x20 &&
  1636. unicode < 0x7F &&
  1637. // " # < > ` (do not escape '?')
  1638. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1
  1639. ) {
  1640. return c;
  1641. }
  1642. return encodeURIComponent(c);
  1643. }
  1644. var EOF, ALPHA = /[a-zA-Z]/,
  1645. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1646. function parse(input, stateOverride, base) {
  1647. function err(message) {
  1648. errors.push(message);
  1649. }
  1650. var state = stateOverride || 'scheme start',
  1651. cursor = 0,
  1652. buffer = '',
  1653. seenAt = false,
  1654. seenBracket = false,
  1655. errors = [];
  1656. loop: while ((input[cursor - 1] !== EOF || cursor === 0) &&
  1657. !this._isInvalid) {
  1658. var c = input[cursor];
  1659. switch (state) {
  1660. case 'scheme start':
  1661. if (c && ALPHA.test(c)) {
  1662. buffer += c.toLowerCase(); // ASCII-safe
  1663. state = 'scheme';
  1664. } else if (!stateOverride) {
  1665. buffer = '';
  1666. state = 'no scheme';
  1667. continue;
  1668. } else {
  1669. err('Invalid scheme.');
  1670. break loop;
  1671. }
  1672. break;
  1673. case 'scheme':
  1674. if (c && ALPHANUMERIC.test(c)) {
  1675. buffer += c.toLowerCase(); // ASCII-safe
  1676. } else if (':' === c) {
  1677. this._scheme = buffer;
  1678. buffer = '';
  1679. if (stateOverride) {
  1680. break loop;
  1681. }
  1682. if (isRelativeScheme(this._scheme)) {
  1683. this._isRelative = true;
  1684. }
  1685. if ('file' === this._scheme) {
  1686. state = 'relative';
  1687. } else if (this._isRelative && base &&
  1688. base._scheme === this._scheme) {
  1689. state = 'relative or authority';
  1690. } else if (this._isRelative) {
  1691. state = 'authority first slash';
  1692. } else {
  1693. state = 'scheme data';
  1694. }
  1695. } else if (!stateOverride) {
  1696. buffer = '';
  1697. cursor = 0;
  1698. state = 'no scheme';
  1699. continue;
  1700. } else if (EOF === c) {
  1701. break loop;
  1702. } else {
  1703. err('Code point not allowed in scheme: ' + c);
  1704. break loop;
  1705. }
  1706. break;
  1707. case 'scheme data':
  1708. if ('?' === c) {
  1709. this._query = '?';
  1710. state = 'query';
  1711. } else if ('#' === c) {
  1712. this._fragment = '#';
  1713. state = 'fragment';
  1714. } else {
  1715. // XXX error handling
  1716. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1717. this._schemeData += percentEscape(c);
  1718. }
  1719. }
  1720. break;
  1721. case 'no scheme':
  1722. if (!base || !(isRelativeScheme(base._scheme))) {
  1723. err('Missing scheme.');
  1724. invalid.call(this);
  1725. } else {
  1726. state = 'relative';
  1727. continue;
  1728. }
  1729. break;
  1730. case 'relative or authority':
  1731. if ('/' === c && '/' === input[cursor+1]) {
  1732. state = 'authority ignore slashes';
  1733. } else {
  1734. err('Expected /, got: ' + c);
  1735. state = 'relative';
  1736. continue;
  1737. }
  1738. break;
  1739. case 'relative':
  1740. this._isRelative = true;
  1741. if ('file' !== this._scheme) {
  1742. this._scheme = base._scheme;
  1743. }
  1744. if (EOF === c) {
  1745. this._host = base._host;
  1746. this._port = base._port;
  1747. this._path = base._path.slice();
  1748. this._query = base._query;
  1749. this._username = base._username;
  1750. this._password = base._password;
  1751. break loop;
  1752. } else if ('/' === c || '\\' === c) {
  1753. if ('\\' === c) {
  1754. err('\\ is an invalid code point.');
  1755. }
  1756. state = 'relative slash';
  1757. } else if ('?' === c) {
  1758. this._host = base._host;
  1759. this._port = base._port;
  1760. this._path = base._path.slice();
  1761. this._query = '?';
  1762. this._username = base._username;
  1763. this._password = base._password;
  1764. state = 'query';
  1765. } else if ('#' === c) {
  1766. this._host = base._host;
  1767. this._port = base._port;
  1768. this._path = base._path.slice();
  1769. this._query = base._query;
  1770. this._fragment = '#';
  1771. this._username = base._username;
  1772. this._password = base._password;
  1773. state = 'fragment';
  1774. } else {
  1775. var nextC = input[cursor+1];
  1776. var nextNextC = input[cursor+2];
  1777. if ('file' !== this._scheme || !ALPHA.test(c) ||
  1778. (nextC !== ':' && nextC !== '|') ||
  1779. (EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC &&
  1780. '?' !== nextNextC && '#' !== nextNextC)) {
  1781. this._host = base._host;
  1782. this._port = base._port;
  1783. this._username = base._username;
  1784. this._password = base._password;
  1785. this._path = base._path.slice();
  1786. this._path.pop();
  1787. }
  1788. state = 'relative path';
  1789. continue;
  1790. }
  1791. break;
  1792. case 'relative slash':
  1793. if ('/' === c || '\\' === c) {
  1794. if ('\\' === c) {
  1795. err('\\ is an invalid code point.');
  1796. }
  1797. if ('file' === this._scheme) {
  1798. state = 'file host';
  1799. } else {
  1800. state = 'authority ignore slashes';
  1801. }
  1802. } else {
  1803. if ('file' !== this._scheme) {
  1804. this._host = base._host;
  1805. this._port = base._port;
  1806. this._username = base._username;
  1807. this._password = base._password;
  1808. }
  1809. state = 'relative path';
  1810. continue;
  1811. }
  1812. break;
  1813. case 'authority first slash':
  1814. if ('/' === c) {
  1815. state = 'authority second slash';
  1816. } else {
  1817. err('Expected \'/\', got: ' + c);
  1818. state = 'authority ignore slashes';
  1819. continue;
  1820. }
  1821. break;
  1822. case 'authority second slash':
  1823. state = 'authority ignore slashes';
  1824. if ('/' !== c) {
  1825. err('Expected \'/\', got: ' + c);
  1826. continue;
  1827. }
  1828. break;
  1829. case 'authority ignore slashes':
  1830. if ('/' !== c && '\\' !== c) {
  1831. state = 'authority';
  1832. continue;
  1833. } else {
  1834. err('Expected authority, got: ' + c);
  1835. }
  1836. break;
  1837. case 'authority':
  1838. if ('@' === c) {
  1839. if (seenAt) {
  1840. err('@ already seen.');
  1841. buffer += '%40';
  1842. }
  1843. seenAt = true;
  1844. for (var i = 0; i < buffer.length; i++) {
  1845. var cp = buffer[i];
  1846. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  1847. err('Invalid whitespace in authority.');
  1848. continue;
  1849. }
  1850. // XXX check URL code points
  1851. if (':' === cp && null === this._password) {
  1852. this._password = '';
  1853. continue;
  1854. }
  1855. var tempC = percentEscape(cp);
  1856. if (null !== this._password) {
  1857. this._password += tempC;
  1858. } else {
  1859. this._username += tempC;
  1860. }
  1861. }
  1862. buffer = '';
  1863. } else if (EOF === c || '/' === c || '\\' === c ||
  1864. '?' === c || '#' === c) {
  1865. cursor -= buffer.length;
  1866. buffer = '';
  1867. state = 'host';
  1868. continue;
  1869. } else {
  1870. buffer += c;
  1871. }
  1872. break;
  1873. case 'file host':
  1874. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  1875. if (buffer.length === 2 && ALPHA.test(buffer[0]) &&
  1876. (buffer[1] === ':' || buffer[1] === '|')) {
  1877. state = 'relative path';
  1878. } else if (buffer.length === 0) {
  1879. state = 'relative path start';
  1880. } else {
  1881. this._host = IDNAToASCII.call(this, buffer);
  1882. buffer = '';
  1883. state = 'relative path start';
  1884. }
  1885. continue;
  1886. } else if ('\t' === c || '\n' === c || '\r' === c) {
  1887. err('Invalid whitespace in file host.');
  1888. } else {
  1889. buffer += c;
  1890. }
  1891. break;
  1892. case 'host':
  1893. case 'hostname':
  1894. if (':' === c && !seenBracket) {
  1895. // XXX host parsing
  1896. this._host = IDNAToASCII.call(this, buffer);
  1897. buffer = '';
  1898. state = 'port';
  1899. if ('hostname' === stateOverride) {
  1900. break loop;
  1901. }
  1902. } else if (EOF === c || '/' === c ||
  1903. '\\' === c || '?' === c || '#' === c) {
  1904. this._host = IDNAToASCII.call(this, buffer);
  1905. buffer = '';
  1906. state = 'relative path start';
  1907. if (stateOverride) {
  1908. break loop;
  1909. }
  1910. continue;
  1911. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1912. if ('[' === c) {
  1913. seenBracket = true;
  1914. } else if (']' === c) {
  1915. seenBracket = false;
  1916. }
  1917. buffer += c;
  1918. } else {
  1919. err('Invalid code point in host/hostname: ' + c);
  1920. }
  1921. break;
  1922. case 'port':
  1923. if (/[0-9]/.test(c)) {
  1924. buffer += c;
  1925. } else if (EOF === c || '/' === c || '\\' === c ||
  1926. '?' === c || '#' === c || stateOverride) {
  1927. if ('' !== buffer) {
  1928. var temp = parseInt(buffer, 10);
  1929. if (temp !== relative[this._scheme]) {
  1930. this._port = temp + '';
  1931. }
  1932. buffer = '';
  1933. }
  1934. if (stateOverride) {
  1935. break loop;
  1936. }
  1937. state = 'relative path start';
  1938. continue;
  1939. } else if ('\t' === c || '\n' === c || '\r' === c) {
  1940. err('Invalid code point in port: ' + c);
  1941. } else {
  1942. invalid.call(this);
  1943. }
  1944. break;
  1945. case 'relative path start':
  1946. if ('\\' === c) {
  1947. err('\'\\\' not allowed in path.');
  1948. }
  1949. state = 'relative path';
  1950. if ('/' !== c && '\\' !== c) {
  1951. continue;
  1952. }
  1953. break;
  1954. case 'relative path':
  1955. if (EOF === c || '/' === c || '\\' === c ||
  1956. (!stateOverride && ('?' === c || '#' === c))) {
  1957. if ('\\' === c) {
  1958. err('\\ not allowed in relative path.');
  1959. }
  1960. var tmp;
  1961. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1962. buffer = tmp;
  1963. }
  1964. if ('..' === buffer) {
  1965. this._path.pop();
  1966. if ('/' !== c && '\\' !== c) {
  1967. this._path.push('');
  1968. }
  1969. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  1970. this._path.push('');
  1971. } else if ('.' !== buffer) {
  1972. if ('file' === this._scheme && this._path.length === 0 &&
  1973. buffer.length === 2 && ALPHA.test(buffer[0]) &&
  1974. buffer[1] === '|') {
  1975. buffer = buffer[0] + ':';
  1976. }
  1977. this._path.push(buffer);
  1978. }
  1979. buffer = '';
  1980. if ('?' === c) {
  1981. this._query = '?';
  1982. state = 'query';
  1983. } else if ('#' === c) {
  1984. this._fragment = '#';
  1985. state = 'fragment';
  1986. }
  1987. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1988. buffer += percentEscape(c);
  1989. }
  1990. break;
  1991. case 'query':
  1992. if (!stateOverride && '#' === c) {
  1993. this._fragment = '#';
  1994. state = 'fragment';
  1995. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1996. this._query += percentEscapeQuery(c);
  1997. }
  1998. break;
  1999. case 'fragment':
  2000. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2001. this._fragment += c;
  2002. }
  2003. break;
  2004. }
  2005. cursor++;
  2006. }
  2007. }
  2008. function clear() {
  2009. this._scheme = '';
  2010. this._schemeData = '';
  2011. this._username = '';
  2012. this._password = null;
  2013. this._host = '';
  2014. this._port = '';
  2015. this._path = [];
  2016. this._query = '';
  2017. this._fragment = '';
  2018. this._isInvalid = false;
  2019. this._isRelative = false;
  2020. }
  2021. // Does not process domain names or IP addresses.
  2022. // Does not handle encoding for the query parameter.
  2023. function JURL(url, base /* , encoding */) {
  2024. if (base !== undefined && !(base instanceof JURL)) {
  2025. base = new JURL(String(base));
  2026. }
  2027. this._url = url;
  2028. clear.call(this);
  2029. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2030. // encoding = encoding || 'utf-8'
  2031. parse.call(this, input, null, base);
  2032. }
  2033. JURL.prototype = {
  2034. toString: function() {
  2035. return this.href;
  2036. },
  2037. get href() {
  2038. if (this._isInvalid) {
  2039. return this._url;
  2040. }
  2041. var authority = '';
  2042. if ('' !== this._username || null !== this._password) {
  2043. authority = this._username +
  2044. (null !== this._password ? ':' + this._password : '') + '@';
  2045. }
  2046. return this.protocol +
  2047. (this._isRelative ? '//' + authority + this.host : '') +
  2048. this.pathname + this._query + this._fragment;
  2049. },
  2050. set href(href) {
  2051. clear.call(this);
  2052. parse.call(this, href);
  2053. },
  2054. get protocol() {
  2055. return this._scheme + ':';
  2056. },
  2057. set protocol(protocol) {
  2058. if (this._isInvalid) {
  2059. return;
  2060. }
  2061. parse.call(this, protocol + ':', 'scheme start');
  2062. },
  2063. get host() {
  2064. return this._isInvalid ? '' : this._port ?
  2065. this._host + ':' + this._port : this._host;
  2066. },
  2067. set host(host) {
  2068. if (this._isInvalid || !this._isRelative) {
  2069. return;
  2070. }
  2071. parse.call(this, host, 'host');
  2072. },
  2073. get hostname() {
  2074. return this._host;
  2075. },
  2076. set hostname(hostname) {
  2077. if (this._isInvalid || !this._isRelative) {
  2078. return;
  2079. }
  2080. parse.call(this, hostname, 'hostname');
  2081. },
  2082. get port() {
  2083. return this._port;
  2084. },
  2085. set port(port) {
  2086. if (this._isInvalid || !this._isRelative) {
  2087. return;
  2088. }
  2089. parse.call(this, port, 'port');
  2090. },
  2091. get pathname() {
  2092. return this._isInvalid ? '' : this._isRelative ?
  2093. '/' + this._path.join('/') : this._schemeData;
  2094. },
  2095. set pathname(pathname) {
  2096. if (this._isInvalid || !this._isRelative) {
  2097. return;
  2098. }
  2099. this._path = [];
  2100. parse.call(this, pathname, 'relative path start');
  2101. },
  2102. get search() {
  2103. return this._isInvalid || !this._query || '?' === this._query ?
  2104. '' : this._query;
  2105. },
  2106. set search(search) {
  2107. if (this._isInvalid || !this._isRelative) {
  2108. return;
  2109. }
  2110. this._query = '?';
  2111. if ('?' === search[0]) {
  2112. search = search.slice(1);
  2113. }
  2114. parse.call(this, search, 'query');
  2115. },
  2116. get hash() {
  2117. return this._isInvalid || !this._fragment || '#' === this._fragment ?
  2118. '' : this._fragment;
  2119. },
  2120. set hash(hash) {
  2121. if (this._isInvalid) {
  2122. return;
  2123. }
  2124. this._fragment = '#';
  2125. if ('#' === hash[0]) {
  2126. hash = hash.slice(1);
  2127. }
  2128. parse.call(this, hash, 'fragment');
  2129. },
  2130. get origin() {
  2131. var host;
  2132. if (this._isInvalid || !this._scheme) {
  2133. return '';
  2134. }
  2135. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2136. // Gecko throws error for "data://"
  2137. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2138. // Gecko returns String("") for file: mailto:
  2139. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2140. switch (this._scheme) {
  2141. case 'data':
  2142. case 'file':
  2143. case 'javascript':
  2144. case 'mailto':
  2145. return 'null';
  2146. }
  2147. host = this.host;
  2148. if (!host) {
  2149. return '';
  2150. }
  2151. return this._scheme + '://' + host;
  2152. }
  2153. };
  2154. // Copy over the static methods
  2155. var OriginalURL = scope.URL;
  2156. if (OriginalURL) {
  2157. JURL.createObjectURL = function(blob) {
  2158. // IE extension allows a second optional options argument.
  2159. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2160. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2161. };
  2162. JURL.revokeObjectURL = function(url) {
  2163. OriginalURL.revokeObjectURL(url);
  2164. };
  2165. }
  2166. scope.URL = JURL;
  2167. })(globalScope);
  2168. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2169. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2170. exports.OPS = OPS;
  2171. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2172. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2173. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2174. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2175. exports.AnnotationFlag = AnnotationFlag;
  2176. exports.AnnotationType = AnnotationType;
  2177. exports.FontType = FontType;
  2178. exports.ImageKind = ImageKind;
  2179. exports.InvalidPDFException = InvalidPDFException;
  2180. exports.MessageHandler = MessageHandler;
  2181. exports.MissingDataException = MissingDataException;
  2182. exports.MissingPDFException = MissingPDFException;
  2183. exports.NotImplementedException = NotImplementedException;
  2184. exports.PageViewport = PageViewport;
  2185. exports.PasswordException = PasswordException;
  2186. exports.PasswordResponses = PasswordResponses;
  2187. exports.StatTimer = StatTimer;
  2188. exports.StreamType = StreamType;
  2189. exports.TextRenderingMode = TextRenderingMode;
  2190. exports.UnexpectedResponseException = UnexpectedResponseException;
  2191. exports.UnknownErrorException = UnknownErrorException;
  2192. exports.Util = Util;
  2193. exports.XRefParseException = XRefParseException;
  2194. exports.arrayByteLength = arrayByteLength;
  2195. exports.arraysToBytes = arraysToBytes;
  2196. exports.assert = assert;
  2197. exports.bytesToString = bytesToString;
  2198. exports.createBlob = createBlob;
  2199. exports.createPromiseCapability = createPromiseCapability;
  2200. exports.createObjectURL = createObjectURL;
  2201. exports.deprecated = deprecated;
  2202. exports.error = error;
  2203. exports.getLookupTableFactory = getLookupTableFactory;
  2204. exports.getVerbosityLevel = getVerbosityLevel;
  2205. exports.globalScope = globalScope;
  2206. exports.info = info;
  2207. exports.isArray = isArray;
  2208. exports.isArrayBuffer = isArrayBuffer;
  2209. exports.isBool = isBool;
  2210. exports.isEmptyObj = isEmptyObj;
  2211. exports.isInt = isInt;
  2212. exports.isNum = isNum;
  2213. exports.isString = isString;
  2214. exports.isSpace = isSpace;
  2215. exports.isSameOrigin = isSameOrigin;
  2216. exports.isValidUrl = isValidUrl;
  2217. exports.isLittleEndian = isLittleEndian;
  2218. exports.isEvalSupported = isEvalSupported;
  2219. exports.loadJpegStream = loadJpegStream;
  2220. exports.log2 = log2;
  2221. exports.readInt8 = readInt8;
  2222. exports.readUint16 = readUint16;
  2223. exports.readUint32 = readUint32;
  2224. exports.removeNullCharacters = removeNullCharacters;
  2225. exports.setVerbosityLevel = setVerbosityLevel;
  2226. exports.shadow = shadow;
  2227. exports.string32 = string32;
  2228. exports.stringToBytes = stringToBytes;
  2229. exports.stringToPDFString = stringToPDFString;
  2230. exports.stringToUTF8String = stringToUTF8String;
  2231. exports.utf8StringToString = utf8StringToString;
  2232. exports.warn = warn;
  2233. }));
  2234. (function (root, factory) {
  2235. {
  2236. factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil);
  2237. }
  2238. }(this, function (exports, sharedUtil) {
  2239. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2240. var warn = sharedUtil.warn;
  2241. /**
  2242. * Optimised CSS custom property getter/setter.
  2243. * @class
  2244. */
  2245. var CustomStyle = (function CustomStyleClosure() {
  2246. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2247. // animate-css-transforms-firefox-webkit.html
  2248. // in some versions of IE9 it is critical that ms appear in this list
  2249. // before Moz
  2250. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  2251. var _cache = Object.create(null);
  2252. function CustomStyle() {}
  2253. CustomStyle.getProp = function get(propName, element) {
  2254. // check cache only when no element is given
  2255. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2256. return _cache[propName];
  2257. }
  2258. element = element || document.documentElement;
  2259. var style = element.style, prefixed, uPropName;
  2260. // test standard property first
  2261. if (typeof style[propName] === 'string') {
  2262. return (_cache[propName] = propName);
  2263. }
  2264. // capitalize
  2265. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2266. // test vendor specific properties
  2267. for (var i = 0, l = prefixes.length; i < l; i++) {
  2268. prefixed = prefixes[i] + uPropName;
  2269. if (typeof style[prefixed] === 'string') {
  2270. return (_cache[propName] = prefixed);
  2271. }
  2272. }
  2273. //if all fails then set to undefined
  2274. return (_cache[propName] = 'undefined');
  2275. };
  2276. CustomStyle.setProp = function set(propName, element, str) {
  2277. var prop = this.getProp(propName);
  2278. if (prop !== 'undefined') {
  2279. element.style[prop] = str;
  2280. }
  2281. };
  2282. return CustomStyle;
  2283. })();
  2284. function hasCanvasTypedArrays() {
  2285. var canvas = document.createElement('canvas');
  2286. canvas.width = canvas.height = 1;
  2287. var ctx = canvas.getContext('2d');
  2288. var imageData = ctx.createImageData(1, 1);
  2289. return (typeof imageData.data.buffer !== 'undefined');
  2290. }
  2291. var LinkTarget = {
  2292. NONE: 0, // Default value.
  2293. SELF: 1,
  2294. BLANK: 2,
  2295. PARENT: 3,
  2296. TOP: 4,
  2297. };
  2298. var LinkTargetStringMap = [
  2299. '',
  2300. '_self',
  2301. '_blank',
  2302. '_parent',
  2303. '_top'
  2304. ];
  2305. /**
  2306. * @typedef ExternalLinkParameters
  2307. * @typedef {Object} ExternalLinkParameters
  2308. * @property {string} url - An absolute URL.
  2309. * @property {LinkTarget} target - The link target.
  2310. * @property {string} rel - The link relationship.
  2311. */
  2312. /**
  2313. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2314. * @param {HTMLLinkElement} link - The link element.
  2315. * @param {ExternalLinkParameters} params
  2316. */
  2317. function addLinkAttributes(link, params) {
  2318. var url = params && params.url;
  2319. link.href = link.title = (url ? removeNullCharacters(url) : '');
  2320. if (url) {
  2321. var target = params.target;
  2322. if (typeof target === 'undefined') {
  2323. target = getDefaultSetting('externalLinkTarget');
  2324. }
  2325. link.target = LinkTargetStringMap[target];
  2326. var rel = params.rel;
  2327. if (typeof rel === 'undefined') {
  2328. rel = getDefaultSetting('externalLinkRel');
  2329. }
  2330. link.rel = rel;
  2331. }
  2332. }
  2333. // Gets the file name from a given URL.
  2334. function getFilenameFromUrl(url) {
  2335. var anchor = url.indexOf('#');
  2336. var query = url.indexOf('?');
  2337. var end = Math.min(
  2338. anchor > 0 ? anchor : url.length,
  2339. query > 0 ? query : url.length);
  2340. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2341. }
  2342. function getDefaultSetting(id) {
  2343. // The list of the settings and their default is maintained for backward
  2344. // compatibility and shall not be extended or modified. See also global.js.
  2345. var globalSettings = sharedUtil.globalScope.PDFJS;
  2346. switch (id) {
  2347. case 'pdfBug':
  2348. return globalSettings ? globalSettings.pdfBug : false;
  2349. case 'disableAutoFetch':
  2350. return globalSettings ? globalSettings.disableAutoFetch : false;
  2351. case 'disableStream':
  2352. return globalSettings ? globalSettings.disableStream : false;
  2353. case 'disableRange':
  2354. return globalSettings ? globalSettings.disableRange : false;
  2355. case 'disableFontFace':
  2356. return globalSettings ? globalSettings.disableFontFace : false;
  2357. case 'disableCreateObjectURL':
  2358. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2359. case 'disableWebGL':
  2360. return globalSettings ? globalSettings.disableWebGL : true;
  2361. case 'cMapUrl':
  2362. return globalSettings ? globalSettings.cMapUrl : null;
  2363. case 'cMapPacked':
  2364. return globalSettings ? globalSettings.cMapPacked : false;
  2365. case 'postMessageTransfers':
  2366. return globalSettings ? globalSettings.postMessageTransfers : true;
  2367. case 'workerSrc':
  2368. return globalSettings ? globalSettings.workerSrc : null;
  2369. case 'disableWorker':
  2370. return globalSettings ? globalSettings.disableWorker : false;
  2371. case 'maxImageSize':
  2372. return globalSettings ? globalSettings.maxImageSize : -1;
  2373. case 'imageResourcesPath':
  2374. return globalSettings ? globalSettings.imageResourcesPath : '';
  2375. case 'isEvalSupported':
  2376. return globalSettings ? globalSettings.isEvalSupported : true;
  2377. case 'externalLinkTarget':
  2378. if (!globalSettings) {
  2379. return LinkTarget.NONE;
  2380. }
  2381. switch (globalSettings.externalLinkTarget) {
  2382. case LinkTarget.NONE:
  2383. case LinkTarget.SELF:
  2384. case LinkTarget.BLANK:
  2385. case LinkTarget.PARENT:
  2386. case LinkTarget.TOP:
  2387. return globalSettings.externalLinkTarget;
  2388. }
  2389. warn('PDFJS.externalLinkTarget is invalid: ' +
  2390. globalSettings.externalLinkTarget);
  2391. // Reset the external link target, to suppress further warnings.
  2392. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2393. return LinkTarget.NONE;
  2394. case 'externalLinkRel':
  2395. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2396. case 'enableStats':
  2397. return !!(globalSettings && globalSettings.enableStats);
  2398. default:
  2399. throw new Error('Unknown default setting: ' + id);
  2400. }
  2401. }
  2402. function isExternalLinkTargetSet() {
  2403. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2404. switch (externalLinkTarget) {
  2405. case LinkTarget.NONE:
  2406. return false;
  2407. case LinkTarget.SELF:
  2408. case LinkTarget.BLANK:
  2409. case LinkTarget.PARENT:
  2410. case LinkTarget.TOP:
  2411. return true;
  2412. }
  2413. }
  2414. exports.CustomStyle = CustomStyle;
  2415. exports.addLinkAttributes = addLinkAttributes;
  2416. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2417. exports.getFilenameFromUrl = getFilenameFromUrl;
  2418. exports.LinkTarget = LinkTarget;
  2419. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2420. exports.getDefaultSetting = getDefaultSetting;
  2421. }));
  2422. (function (root, factory) {
  2423. {
  2424. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil);
  2425. }
  2426. }(this, function (exports, sharedUtil) {
  2427. var assert = sharedUtil.assert;
  2428. var bytesToString = sharedUtil.bytesToString;
  2429. var string32 = sharedUtil.string32;
  2430. var shadow = sharedUtil.shadow;
  2431. var warn = sharedUtil.warn;
  2432. function FontLoader(docId) {
  2433. this.docId = docId;
  2434. this.styleElement = null;
  2435. this.nativeFontFaces = [];
  2436. this.loadTestFontId = 0;
  2437. this.loadingContext = {
  2438. requests: [],
  2439. nextRequestId: 0
  2440. };
  2441. }
  2442. FontLoader.prototype = {
  2443. insertRule: function fontLoaderInsertRule(rule) {
  2444. var styleElement = this.styleElement;
  2445. if (!styleElement) {
  2446. styleElement = this.styleElement = document.createElement('style');
  2447. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2448. document.documentElement.getElementsByTagName('head')[0].appendChild(
  2449. styleElement);
  2450. }
  2451. var styleSheet = styleElement.sheet;
  2452. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2453. },
  2454. clear: function fontLoaderClear() {
  2455. var styleElement = this.styleElement;
  2456. if (styleElement) {
  2457. styleElement.parentNode.removeChild(styleElement);
  2458. styleElement = this.styleElement = null;
  2459. }
  2460. this.nativeFontFaces.forEach(function(nativeFontFace) {
  2461. document.fonts.delete(nativeFontFace);
  2462. });
  2463. this.nativeFontFaces.length = 0;
  2464. },
  2465. get loadTestFont() {
  2466. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2467. // height.
  2468. return shadow(this, 'loadTestFont', atob(
  2469. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  2470. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  2471. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  2472. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  2473. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  2474. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  2475. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  2476. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  2477. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  2478. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  2479. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  2480. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  2481. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  2482. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2483. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2484. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2485. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  2486. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  2487. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  2488. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  2489. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  2490. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  2491. ));
  2492. },
  2493. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  2494. this.nativeFontFaces.push(nativeFontFace);
  2495. document.fonts.add(nativeFontFace);
  2496. },
  2497. bind: function fontLoaderBind(fonts, callback) {
  2498. var rules = [];
  2499. var fontsToLoad = [];
  2500. var fontLoadPromises = [];
  2501. var getNativeFontPromise = function(nativeFontFace) {
  2502. // Return a promise that is always fulfilled, even when the font fails to
  2503. // load.
  2504. return nativeFontFace.loaded.catch(function(e) {
  2505. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2506. });
  2507. };
  2508. // Firefox Font Loading API does not work with mozPrintCallback --
  2509. // disabling it in this case.
  2510. var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported &&
  2511. !FontLoader.isSyncFontLoadingSupported;
  2512. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2513. var font = fonts[i];
  2514. // Add the font to the DOM only once or skip if the font
  2515. // is already loaded.
  2516. if (font.attached || font.loading === false) {
  2517. continue;
  2518. }
  2519. font.attached = true;
  2520. if (isFontLoadingAPISupported) {
  2521. var nativeFontFace = font.createNativeFontFace();
  2522. if (nativeFontFace) {
  2523. this.addNativeFontFace(nativeFontFace);
  2524. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2525. }
  2526. } else {
  2527. var rule = font.createFontFaceRule();
  2528. if (rule) {
  2529. this.insertRule(rule);
  2530. rules.push(rule);
  2531. fontsToLoad.push(font);
  2532. }
  2533. }
  2534. }
  2535. var request = this.queueLoadingCallback(callback);
  2536. if (isFontLoadingAPISupported) {
  2537. Promise.all(fontLoadPromises).then(function() {
  2538. request.complete();
  2539. });
  2540. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2541. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2542. } else {
  2543. request.complete();
  2544. }
  2545. },
  2546. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  2547. function LoadLoader_completeRequest() {
  2548. assert(!request.end, 'completeRequest() cannot be called twice');
  2549. request.end = Date.now();
  2550. // sending all completed requests in order how they were queued
  2551. while (context.requests.length > 0 && context.requests[0].end) {
  2552. var otherRequest = context.requests.shift();
  2553. setTimeout(otherRequest.callback, 0);
  2554. }
  2555. }
  2556. var context = this.loadingContext;
  2557. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  2558. var request = {
  2559. id: requestId,
  2560. complete: LoadLoader_completeRequest,
  2561. callback: callback,
  2562. started: Date.now()
  2563. };
  2564. context.requests.push(request);
  2565. return request;
  2566. },
  2567. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  2568. fonts,
  2569. request) {
  2570. /** Hack begin */
  2571. // There's currently no event when a font has finished downloading so the
  2572. // following code is a dirty hack to 'guess' when a font is
  2573. // ready. It's assumed fonts are loaded in order, so add a known test
  2574. // font after the desired fonts and then test for the loading of that
  2575. // test font.
  2576. function int32(data, offset) {
  2577. return (data.charCodeAt(offset) << 24) |
  2578. (data.charCodeAt(offset + 1) << 16) |
  2579. (data.charCodeAt(offset + 2) << 8) |
  2580. (data.charCodeAt(offset + 3) & 0xff);
  2581. }
  2582. function spliceString(s, offset, remove, insert) {
  2583. var chunk1 = s.substr(0, offset);
  2584. var chunk2 = s.substr(offset + remove);
  2585. return chunk1 + insert + chunk2;
  2586. }
  2587. var i, ii;
  2588. var canvas = document.createElement('canvas');
  2589. canvas.width = 1;
  2590. canvas.height = 1;
  2591. var ctx = canvas.getContext('2d');
  2592. var called = 0;
  2593. function isFontReady(name, callback) {
  2594. called++;
  2595. // With setTimeout clamping this gives the font ~100ms to load.
  2596. if(called > 30) {
  2597. warn('Load test font never loaded.');
  2598. callback();
  2599. return;
  2600. }
  2601. ctx.font = '30px ' + name;
  2602. ctx.fillText('.', 0, 20);
  2603. var imageData = ctx.getImageData(0, 0, 1, 1);
  2604. if (imageData.data[3] > 0) {
  2605. callback();
  2606. return;
  2607. }
  2608. setTimeout(isFontReady.bind(null, name, callback));
  2609. }
  2610. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2611. // Chromium seems to cache fonts based on a hash of the actual font data,
  2612. // so the font must be modified for each load test else it will appear to
  2613. // be loaded already.
  2614. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2615. // font by splitting it in chunks before hand and padding the font id.
  2616. var data = this.loadTestFont;
  2617. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  2618. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  2619. loadTestFontId);
  2620. // CFF checksum is important for IE, adjusting it
  2621. var CFF_CHECKSUM_OFFSET = 16;
  2622. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  2623. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2624. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2625. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  2626. }
  2627. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  2628. checksum = (checksum - XXXX_VALUE +
  2629. int32(loadTestFontId + 'XXX', i)) | 0;
  2630. }
  2631. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2632. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2633. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  2634. url + '}';
  2635. this.insertRule(rule);
  2636. var names = [];
  2637. for (i = 0, ii = fonts.length; i < ii; i++) {
  2638. names.push(fonts[i].loadedName);
  2639. }
  2640. names.push(loadTestFontId);
  2641. var div = document.createElement('div');
  2642. div.setAttribute('style',
  2643. 'visibility: hidden;' +
  2644. 'width: 10px; height: 10px;' +
  2645. 'position: absolute; top: 0px; left: 0px;');
  2646. for (i = 0, ii = names.length; i < ii; ++i) {
  2647. var span = document.createElement('span');
  2648. span.textContent = 'Hi';
  2649. span.style.fontFamily = names[i];
  2650. div.appendChild(span);
  2651. }
  2652. document.body.appendChild(div);
  2653. isFontReady(loadTestFontId, function() {
  2654. document.body.removeChild(div);
  2655. request.complete();
  2656. });
  2657. /** Hack end */
  2658. }
  2659. };
  2660. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' &&
  2661. !!document.fonts;
  2662. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2663. get: function () {
  2664. if (typeof navigator === 'undefined') {
  2665. // node.js - we can pretend sync font loading is supported.
  2666. return shadow(FontLoader, 'isSyncFontLoadingSupported', true);
  2667. }
  2668. var supported = false;
  2669. // User agent string sniffing is bad, but there is no reliable way to tell
  2670. // if font is fully loaded and ready to be used with canvas.
  2671. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2672. if (m && m[1] >= 14) {
  2673. supported = true;
  2674. }
  2675. // TODO other browsers
  2676. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  2677. },
  2678. enumerable: true,
  2679. configurable: true
  2680. });
  2681. var IsEvalSupportedCached = {
  2682. get value() {
  2683. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2684. }
  2685. };
  2686. var FontFaceObject = (function FontFaceObjectClosure() {
  2687. function FontFaceObject(translatedData, options) {
  2688. this.compiledGlyphs = Object.create(null);
  2689. // importing translated data
  2690. for (var i in translatedData) {
  2691. this[i] = translatedData[i];
  2692. }
  2693. this.options = options;
  2694. }
  2695. FontFaceObject.prototype = {
  2696. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2697. if (!this.data) {
  2698. return null;
  2699. }
  2700. if (this.options.disableFontFace) {
  2701. this.disableFontFace = true;
  2702. return null;
  2703. }
  2704. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2705. if (this.options.fontRegistry) {
  2706. this.options.fontRegistry.registerFont(this);
  2707. }
  2708. return nativeFontFace;
  2709. },
  2710. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2711. if (!this.data) {
  2712. return null;
  2713. }
  2714. if (this.options.disableFontFace) {
  2715. this.disableFontFace = true;
  2716. return null;
  2717. }
  2718. var data = bytesToString(new Uint8Array(this.data));
  2719. var fontName = this.loadedName;
  2720. // Add the font-face rule to the document
  2721. var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');');
  2722. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2723. if (this.options.fontRegistry) {
  2724. this.options.fontRegistry.registerFont(this, url);
  2725. }
  2726. return rule;
  2727. },
  2728. getPathGenerator:
  2729. function FontFaceObject_getPathGenerator(objs, character) {
  2730. if (!(character in this.compiledGlyphs)) {
  2731. var cmds = objs.get(this.loadedName + '_path_' + character);
  2732. var current, i, len;
  2733. // If we can, compile cmds into JS for MAXIMUM SPEED
  2734. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2735. var args, js = '';
  2736. for (i = 0, len = cmds.length; i < len; i++) {
  2737. current = cmds[i];
  2738. if (current.args !== undefined) {
  2739. args = current.args.join(',');
  2740. } else {
  2741. args = '';
  2742. }
  2743. js += 'c.' + current.cmd + '(' + args + ');\n';
  2744. }
  2745. /* jshint -W054 */
  2746. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2747. } else {
  2748. // But fall back on using Function.prototype.apply() if we're
  2749. // blocked from using eval() for whatever reason (like CSP policies)
  2750. this.compiledGlyphs[character] = function(c, size) {
  2751. for (i = 0, len = cmds.length; i < len; i++) {
  2752. current = cmds[i];
  2753. if (current.cmd === 'scale') {
  2754. current.args = [size, -size];
  2755. }
  2756. c[current.cmd].apply(c, current.args);
  2757. }
  2758. };
  2759. }
  2760. }
  2761. return this.compiledGlyphs[character];
  2762. }
  2763. };
  2764. return FontFaceObject;
  2765. })();
  2766. exports.FontFaceObject = FontFaceObject;
  2767. exports.FontLoader = FontLoader;
  2768. }));
  2769. (function (root, factory) {
  2770. {
  2771. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  2772. }
  2773. }(this, function (exports, sharedUtil) {
  2774. var error = sharedUtil.error;
  2775. function fixMetadata(meta) {
  2776. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2777. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2778. function(code, d1, d2, d3) {
  2779. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2780. });
  2781. var chars = '';
  2782. for (var i = 0; i < bytes.length; i += 2) {
  2783. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2784. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2785. code !== 38 && false ? String.fromCharCode(code) :
  2786. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2787. }
  2788. return '>' + chars;
  2789. });
  2790. }
  2791. function Metadata(meta) {
  2792. if (typeof meta === 'string') {
  2793. // Ghostscript produces invalid metadata
  2794. meta = fixMetadata(meta);
  2795. var parser = new DOMParser();
  2796. meta = parser.parseFromString(meta, 'application/xml');
  2797. } else if (!(meta instanceof Document)) {
  2798. error('Metadata: Invalid metadata object');
  2799. }
  2800. this.metaDocument = meta;
  2801. this.metadata = Object.create(null);
  2802. this.parse();
  2803. }
  2804. Metadata.prototype = {
  2805. parse: function Metadata_parse() {
  2806. var doc = this.metaDocument;
  2807. var rdf = doc.documentElement;
  2808. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2809. rdf = rdf.firstChild;
  2810. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2811. rdf = rdf.nextSibling;
  2812. }
  2813. }
  2814. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2815. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2816. return;
  2817. }
  2818. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2819. for (i = 0, length = children.length; i < length; i++) {
  2820. desc = children[i];
  2821. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2822. continue;
  2823. }
  2824. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2825. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2826. entry = desc.childNodes[ii];
  2827. name = entry.nodeName.toLowerCase();
  2828. this.metadata[name] = entry.textContent.trim();
  2829. }
  2830. }
  2831. }
  2832. },
  2833. get: function Metadata_get(name) {
  2834. return this.metadata[name] || null;
  2835. },
  2836. has: function Metadata_has(name) {
  2837. return typeof this.metadata[name] !== 'undefined';
  2838. }
  2839. };
  2840. exports.Metadata = Metadata;
  2841. }));
  2842. (function (root, factory) {
  2843. {
  2844. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  2845. }
  2846. }(this, function (exports, sharedUtil) {
  2847. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  2848. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  2849. var ImageKind = sharedUtil.ImageKind;
  2850. var OPS = sharedUtil.OPS;
  2851. var Util = sharedUtil.Util;
  2852. var isNum = sharedUtil.isNum;
  2853. var isArray = sharedUtil.isArray;
  2854. var warn = sharedUtil.warn;
  2855. var createObjectURL = sharedUtil.createObjectURL;
  2856. var SVG_DEFAULTS = {
  2857. fontStyle: 'normal',
  2858. fontWeight: 'normal',
  2859. fillColor: '#000000'
  2860. };
  2861. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  2862. var PNG_HEADER =
  2863. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  2864. var CHUNK_WRAPPER_SIZE = 12;
  2865. var crcTable = new Int32Array(256);
  2866. for (var i = 0; i < 256; i++) {
  2867. var c = i;
  2868. for (var h = 0; h < 8; h++) {
  2869. if (c & 1) {
  2870. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  2871. } else {
  2872. c = (c >> 1) & 0x7fffffff;
  2873. }
  2874. }
  2875. crcTable[i] = c;
  2876. }
  2877. function crc32(data, start, end) {
  2878. var crc = -1;
  2879. for (var i = start; i < end; i++) {
  2880. var a = (crc ^ data[i]) & 0xff;
  2881. var b = crcTable[a];
  2882. crc = (crc >>> 8) ^ b;
  2883. }
  2884. return crc ^ -1;
  2885. }
  2886. function writePngChunk(type, body, data, offset) {
  2887. var p = offset;
  2888. var len = body.length;
  2889. data[p] = len >> 24 & 0xff;
  2890. data[p + 1] = len >> 16 & 0xff;
  2891. data[p + 2] = len >> 8 & 0xff;
  2892. data[p + 3] = len & 0xff;
  2893. p += 4;
  2894. data[p] = type.charCodeAt(0) & 0xff;
  2895. data[p + 1] = type.charCodeAt(1) & 0xff;
  2896. data[p + 2] = type.charCodeAt(2) & 0xff;
  2897. data[p + 3] = type.charCodeAt(3) & 0xff;
  2898. p += 4;
  2899. data.set(body, p);
  2900. p += body.length;
  2901. var crc = crc32(data, offset + 4, p);
  2902. data[p] = crc >> 24 & 0xff;
  2903. data[p + 1] = crc >> 16 & 0xff;
  2904. data[p + 2] = crc >> 8 & 0xff;
  2905. data[p + 3] = crc & 0xff;
  2906. }
  2907. function adler32(data, start, end) {
  2908. var a = 1;
  2909. var b = 0;
  2910. for (var i = start; i < end; ++i) {
  2911. a = (a + (data[i] & 0xff)) % 65521;
  2912. b = (b + a) % 65521;
  2913. }
  2914. return (b << 16) | a;
  2915. }
  2916. function encode(imgData, kind, forceDataSchema) {
  2917. var width = imgData.width;
  2918. var height = imgData.height;
  2919. var bitDepth, colorType, lineSize;
  2920. var bytes = imgData.data;
  2921. switch (kind) {
  2922. case ImageKind.GRAYSCALE_1BPP:
  2923. colorType = 0;
  2924. bitDepth = 1;
  2925. lineSize = (width + 7) >> 3;
  2926. break;
  2927. case ImageKind.RGB_24BPP:
  2928. colorType = 2;
  2929. bitDepth = 8;
  2930. lineSize = width * 3;
  2931. break;
  2932. case ImageKind.RGBA_32BPP:
  2933. colorType = 6;
  2934. bitDepth = 8;
  2935. lineSize = width * 4;
  2936. break;
  2937. default:
  2938. throw new Error('invalid format');
  2939. }
  2940. // prefix every row with predictor 0
  2941. var literals = new Uint8Array((1 + lineSize) * height);
  2942. var offsetLiterals = 0, offsetBytes = 0;
  2943. var y, i;
  2944. for (y = 0; y < height; ++y) {
  2945. literals[offsetLiterals++] = 0; // no prediction
  2946. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  2947. offsetLiterals);
  2948. offsetBytes += lineSize;
  2949. offsetLiterals += lineSize;
  2950. }
  2951. if (kind === ImageKind.GRAYSCALE_1BPP) {
  2952. // inverting for B/W
  2953. offsetLiterals = 0;
  2954. for (y = 0; y < height; y++) {
  2955. offsetLiterals++; // skipping predictor
  2956. for (i = 0; i < lineSize; i++) {
  2957. literals[offsetLiterals++] ^= 0xFF;
  2958. }
  2959. }
  2960. }
  2961. var ihdr = new Uint8Array([
  2962. width >> 24 & 0xff,
  2963. width >> 16 & 0xff,
  2964. width >> 8 & 0xff,
  2965. width & 0xff,
  2966. height >> 24 & 0xff,
  2967. height >> 16 & 0xff,
  2968. height >> 8 & 0xff,
  2969. height & 0xff,
  2970. bitDepth, // bit depth
  2971. colorType, // color type
  2972. 0x00, // compression method
  2973. 0x00, // filter method
  2974. 0x00 // interlace method
  2975. ]);
  2976. var len = literals.length;
  2977. var maxBlockLength = 0xFFFF;
  2978. var deflateBlocks = Math.ceil(len / maxBlockLength);
  2979. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  2980. var pi = 0;
  2981. idat[pi++] = 0x78; // compression method and flags
  2982. idat[pi++] = 0x9c; // flags
  2983. var pos = 0;
  2984. while (len > maxBlockLength) {
  2985. // writing non-final DEFLATE blocks type 0 and length of 65535
  2986. idat[pi++] = 0x00;
  2987. idat[pi++] = 0xff;
  2988. idat[pi++] = 0xff;
  2989. idat[pi++] = 0x00;
  2990. idat[pi++] = 0x00;
  2991. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  2992. pi += maxBlockLength;
  2993. pos += maxBlockLength;
  2994. len -= maxBlockLength;
  2995. }
  2996. // writing non-final DEFLATE blocks type 0
  2997. idat[pi++] = 0x01;
  2998. idat[pi++] = len & 0xff;
  2999. idat[pi++] = len >> 8 & 0xff;
  3000. idat[pi++] = (~len & 0xffff) & 0xff;
  3001. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3002. idat.set(literals.subarray(pos), pi);
  3003. pi += literals.length - pos;
  3004. var adler = adler32(literals, 0, literals.length); // checksum
  3005. idat[pi++] = adler >> 24 & 0xff;
  3006. idat[pi++] = adler >> 16 & 0xff;
  3007. idat[pi++] = adler >> 8 & 0xff;
  3008. idat[pi++] = adler & 0xff;
  3009. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3010. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  3011. ihdr.length + idat.length;
  3012. var data = new Uint8Array(pngLength);
  3013. var offset = 0;
  3014. data.set(PNG_HEADER, offset);
  3015. offset += PNG_HEADER.length;
  3016. writePngChunk('IHDR', ihdr, data, offset);
  3017. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3018. writePngChunk('IDATA', idat, data, offset);
  3019. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3020. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3021. return createObjectURL(data, 'image/png', forceDataSchema);
  3022. }
  3023. return function convertImgDataToPng(imgData, forceDataSchema) {
  3024. var kind = (imgData.kind === undefined ?
  3025. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  3026. return encode(imgData, kind, forceDataSchema);
  3027. };
  3028. })();
  3029. var SVGExtraState = (function SVGExtraStateClosure() {
  3030. function SVGExtraState() {
  3031. this.fontSizeScale = 1;
  3032. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3033. this.fontSize = 0;
  3034. this.textMatrix = IDENTITY_MATRIX;
  3035. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3036. this.leading = 0;
  3037. // Current point (in user coordinates)
  3038. this.x = 0;
  3039. this.y = 0;
  3040. // Start of text line (in text coordinates)
  3041. this.lineX = 0;
  3042. this.lineY = 0;
  3043. // Character and word spacing
  3044. this.charSpacing = 0;
  3045. this.wordSpacing = 0;
  3046. this.textHScale = 1;
  3047. this.textRise = 0;
  3048. // Default foreground and background colors
  3049. this.fillColor = SVG_DEFAULTS.fillColor;
  3050. this.strokeColor = '#000000';
  3051. this.fillAlpha = 1;
  3052. this.strokeAlpha = 1;
  3053. this.lineWidth = 1;
  3054. this.lineJoin = '';
  3055. this.lineCap = '';
  3056. this.miterLimit = 0;
  3057. this.dashArray = [];
  3058. this.dashPhase = 0;
  3059. this.dependencies = [];
  3060. // Clipping
  3061. this.clipId = '';
  3062. this.pendingClip = false;
  3063. this.maskId = '';
  3064. }
  3065. SVGExtraState.prototype = {
  3066. clone: function SVGExtraState_clone() {
  3067. return Object.create(this);
  3068. },
  3069. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3070. this.x = x;
  3071. this.y = y;
  3072. }
  3073. };
  3074. return SVGExtraState;
  3075. })();
  3076. var SVGGraphics = (function SVGGraphicsClosure() {
  3077. function createScratchSVG(width, height) {
  3078. var NS = 'http://www.w3.org/2000/svg';
  3079. var svg = document.createElementNS(NS, 'svg:svg');
  3080. svg.setAttributeNS(null, 'version', '1.1');
  3081. svg.setAttributeNS(null, 'width', width + 'px');
  3082. svg.setAttributeNS(null, 'height', height + 'px');
  3083. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3084. return svg;
  3085. }
  3086. function opListToTree(opList) {
  3087. var opTree = [];
  3088. var tmp = [];
  3089. var opListLen = opList.length;
  3090. for (var x = 0; x < opListLen; x++) {
  3091. if (opList[x].fn === 'save') {
  3092. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3093. tmp.push(opTree);
  3094. opTree = opTree[opTree.length - 1].items;
  3095. continue;
  3096. }
  3097. if(opList[x].fn === 'restore') {
  3098. opTree = tmp.pop();
  3099. } else {
  3100. opTree.push(opList[x]);
  3101. }
  3102. }
  3103. return opTree;
  3104. }
  3105. /**
  3106. * Formats float number.
  3107. * @param value {number} number to format.
  3108. * @returns {string}
  3109. */
  3110. function pf(value) {
  3111. if (value === (value | 0)) { // integer number
  3112. return value.toString();
  3113. }
  3114. var s = value.toFixed(10);
  3115. var i = s.length - 1;
  3116. if (s[i] !== '0') {
  3117. return s;
  3118. }
  3119. // removing trailing zeros
  3120. do {
  3121. i--;
  3122. } while (s[i] === '0');
  3123. return s.substr(0, s[i] === '.' ? i : i + 1);
  3124. }
  3125. /**
  3126. * Formats transform matrix. The standard rotation, scale and translate
  3127. * matrices are replaced by their shorter forms, and for identity matrix
  3128. * returns empty string to save the memory.
  3129. * @param m {Array} matrix to format.
  3130. * @returns {string}
  3131. */
  3132. function pm(m) {
  3133. if (m[4] === 0 && m[5] === 0) {
  3134. if (m[1] === 0 && m[2] === 0) {
  3135. if (m[0] === 1 && m[3] === 1) {
  3136. return '';
  3137. }
  3138. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3139. }
  3140. if (m[0] === m[3] && m[1] === -m[2]) {
  3141. var a = Math.acos(m[0]) * 180 / Math.PI;
  3142. return 'rotate(' + pf(a) + ')';
  3143. }
  3144. } else {
  3145. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3146. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3147. }
  3148. }
  3149. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3150. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3151. }
  3152. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3153. this.current = new SVGExtraState();
  3154. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3155. this.transformStack = [];
  3156. this.extraStack = [];
  3157. this.commonObjs = commonObjs;
  3158. this.objs = objs;
  3159. this.pendingEOFill = false;
  3160. this.embedFonts = false;
  3161. this.embeddedFonts = Object.create(null);
  3162. this.cssStyle = null;
  3163. this.forceDataSchema = !!forceDataSchema;
  3164. }
  3165. var NS = 'http://www.w3.org/2000/svg';
  3166. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3167. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3168. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3169. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3170. var clipCount = 0;
  3171. var maskCount = 0;
  3172. SVGGraphics.prototype = {
  3173. save: function SVGGraphics_save() {
  3174. this.transformStack.push(this.transformMatrix);
  3175. var old = this.current;
  3176. this.extraStack.push(old);
  3177. this.current = old.clone();
  3178. },
  3179. restore: function SVGGraphics_restore() {
  3180. this.transformMatrix = this.transformStack.pop();
  3181. this.current = this.extraStack.pop();
  3182. this.tgrp = document.createElementNS(NS, 'svg:g');
  3183. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3184. this.pgrp.appendChild(this.tgrp);
  3185. },
  3186. group: function SVGGraphics_group(items) {
  3187. this.save();
  3188. this.executeOpTree(items);
  3189. this.restore();
  3190. },
  3191. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3192. var fnArray = operatorList.fnArray;
  3193. var fnArrayLen = fnArray.length;
  3194. var argsArray = operatorList.argsArray;
  3195. var self = this;
  3196. for (var i = 0; i < fnArrayLen; i++) {
  3197. if (OPS.dependency === fnArray[i]) {
  3198. var deps = argsArray[i];
  3199. for (var n = 0, nn = deps.length; n < nn; n++) {
  3200. var obj = deps[n];
  3201. var common = obj.substring(0, 2) === 'g_';
  3202. var promise;
  3203. if (common) {
  3204. promise = new Promise(function(resolve) {
  3205. self.commonObjs.get(obj, resolve);
  3206. });
  3207. } else {
  3208. promise = new Promise(function(resolve) {
  3209. self.objs.get(obj, resolve);
  3210. });
  3211. }
  3212. this.current.dependencies.push(promise);
  3213. }
  3214. }
  3215. }
  3216. return Promise.all(this.current.dependencies);
  3217. },
  3218. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3219. var transformMatrix = [a, b, c, d, e, f];
  3220. this.transformMatrix = Util.transform(this.transformMatrix,
  3221. transformMatrix);
  3222. this.tgrp = document.createElementNS(NS, 'svg:g');
  3223. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3224. },
  3225. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3226. this.svg = createScratchSVG(viewport.width, viewport.height);
  3227. this.viewport = viewport;
  3228. return this.loadDependencies(operatorList).then(function () {
  3229. this.transformMatrix = IDENTITY_MATRIX;
  3230. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3231. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3232. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3233. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3234. this.defs = document.createElementNS(NS, 'svg:defs');
  3235. this.pgrp.appendChild(this.defs);
  3236. this.pgrp.appendChild(this.tgrp);
  3237. this.svg.appendChild(this.pgrp);
  3238. var opTree = this.convertOpList(operatorList);
  3239. this.executeOpTree(opTree);
  3240. return this.svg;
  3241. }.bind(this));
  3242. },
  3243. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3244. var argsArray = operatorList.argsArray;
  3245. var fnArray = operatorList.fnArray;
  3246. var fnArrayLen = fnArray.length;
  3247. var REVOPS = [];
  3248. var opList = [];
  3249. for (var op in OPS) {
  3250. REVOPS[OPS[op]] = op;
  3251. }
  3252. for (var x = 0; x < fnArrayLen; x++) {
  3253. var fnId = fnArray[x];
  3254. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3255. }
  3256. return opListToTree(opList);
  3257. },
  3258. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3259. var opTreeLen = opTree.length;
  3260. for(var x = 0; x < opTreeLen; x++) {
  3261. var fn = opTree[x].fn;
  3262. var fnId = opTree[x].fnId;
  3263. var args = opTree[x].args;
  3264. switch (fnId | 0) {
  3265. case OPS.beginText:
  3266. this.beginText();
  3267. break;
  3268. case OPS.setLeading:
  3269. this.setLeading(args);
  3270. break;
  3271. case OPS.setLeadingMoveText:
  3272. this.setLeadingMoveText(args[0], args[1]);
  3273. break;
  3274. case OPS.setFont:
  3275. this.setFont(args);
  3276. break;
  3277. case OPS.showText:
  3278. this.showText(args[0]);
  3279. break;
  3280. case OPS.showSpacedText:
  3281. this.showText(args[0]);
  3282. break;
  3283. case OPS.endText:
  3284. this.endText();
  3285. break;
  3286. case OPS.moveText:
  3287. this.moveText(args[0], args[1]);
  3288. break;
  3289. case OPS.setCharSpacing:
  3290. this.setCharSpacing(args[0]);
  3291. break;
  3292. case OPS.setWordSpacing:
  3293. this.setWordSpacing(args[0]);
  3294. break;
  3295. case OPS.setHScale:
  3296. this.setHScale(args[0]);
  3297. break;
  3298. case OPS.setTextMatrix:
  3299. this.setTextMatrix(args[0], args[1], args[2],
  3300. args[3], args[4], args[5]);
  3301. break;
  3302. case OPS.setLineWidth:
  3303. this.setLineWidth(args[0]);
  3304. break;
  3305. case OPS.setLineJoin:
  3306. this.setLineJoin(args[0]);
  3307. break;
  3308. case OPS.setLineCap:
  3309. this.setLineCap(args[0]);
  3310. break;
  3311. case OPS.setMiterLimit:
  3312. this.setMiterLimit(args[0]);
  3313. break;
  3314. case OPS.setFillRGBColor:
  3315. this.setFillRGBColor(args[0], args[1], args[2]);
  3316. break;
  3317. case OPS.setStrokeRGBColor:
  3318. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3319. break;
  3320. case OPS.setDash:
  3321. this.setDash(args[0], args[1]);
  3322. break;
  3323. case OPS.setGState:
  3324. this.setGState(args[0]);
  3325. break;
  3326. case OPS.fill:
  3327. this.fill();
  3328. break;
  3329. case OPS.eoFill:
  3330. this.eoFill();
  3331. break;
  3332. case OPS.stroke:
  3333. this.stroke();
  3334. break;
  3335. case OPS.fillStroke:
  3336. this.fillStroke();
  3337. break;
  3338. case OPS.eoFillStroke:
  3339. this.eoFillStroke();
  3340. break;
  3341. case OPS.clip:
  3342. this.clip('nonzero');
  3343. break;
  3344. case OPS.eoClip:
  3345. this.clip('evenodd');
  3346. break;
  3347. case OPS.paintSolidColorImageMask:
  3348. this.paintSolidColorImageMask();
  3349. break;
  3350. case OPS.paintJpegXObject:
  3351. this.paintJpegXObject(args[0], args[1], args[2]);
  3352. break;
  3353. case OPS.paintImageXObject:
  3354. this.paintImageXObject(args[0]);
  3355. break;
  3356. case OPS.paintInlineImageXObject:
  3357. this.paintInlineImageXObject(args[0]);
  3358. break;
  3359. case OPS.paintImageMaskXObject:
  3360. this.paintImageMaskXObject(args[0]);
  3361. break;
  3362. case OPS.paintFormXObjectBegin:
  3363. this.paintFormXObjectBegin(args[0], args[1]);
  3364. break;
  3365. case OPS.paintFormXObjectEnd:
  3366. this.paintFormXObjectEnd();
  3367. break;
  3368. case OPS.closePath:
  3369. this.closePath();
  3370. break;
  3371. case OPS.closeStroke:
  3372. this.closeStroke();
  3373. break;
  3374. case OPS.closeFillStroke:
  3375. this.closeFillStroke();
  3376. break;
  3377. case OPS.nextLine:
  3378. this.nextLine();
  3379. break;
  3380. case OPS.transform:
  3381. this.transform(args[0], args[1], args[2], args[3],
  3382. args[4], args[5]);
  3383. break;
  3384. case OPS.constructPath:
  3385. this.constructPath(args[0], args[1]);
  3386. break;
  3387. case OPS.endPath:
  3388. this.endPath();
  3389. break;
  3390. case 92:
  3391. this.group(opTree[x].items);
  3392. break;
  3393. default:
  3394. warn('Unimplemented method '+ fn);
  3395. break;
  3396. }
  3397. }
  3398. },
  3399. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3400. this.current.wordSpacing = wordSpacing;
  3401. },
  3402. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3403. this.current.charSpacing = charSpacing;
  3404. },
  3405. nextLine: function SVGGraphics_nextLine() {
  3406. this.moveText(0, this.current.leading);
  3407. },
  3408. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3409. var current = this.current;
  3410. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  3411. this.current.x = this.current.lineX = 0;
  3412. this.current.y = this.current.lineY = 0;
  3413. current.xcoords = [];
  3414. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3415. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3416. current.tspan.setAttributeNS(null, 'font-size',
  3417. pf(current.fontSize) + 'px');
  3418. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3419. current.txtElement = document.createElementNS(NS, 'svg:text');
  3420. current.txtElement.appendChild(current.tspan);
  3421. },
  3422. beginText: function SVGGraphics_beginText() {
  3423. this.current.x = this.current.lineX = 0;
  3424. this.current.y = this.current.lineY = 0;
  3425. this.current.textMatrix = IDENTITY_MATRIX;
  3426. this.current.lineMatrix = IDENTITY_MATRIX;
  3427. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3428. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3429. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3430. this.current.xcoords = [];
  3431. },
  3432. moveText: function SVGGraphics_moveText(x, y) {
  3433. var current = this.current;
  3434. this.current.x = this.current.lineX += x;
  3435. this.current.y = this.current.lineY += y;
  3436. current.xcoords = [];
  3437. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3438. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3439. current.tspan.setAttributeNS(null, 'font-size',
  3440. pf(current.fontSize) + 'px');
  3441. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3442. },
  3443. showText: function SVGGraphics_showText(glyphs) {
  3444. var current = this.current;
  3445. var font = current.font;
  3446. var fontSize = current.fontSize;
  3447. if (fontSize === 0) {
  3448. return;
  3449. }
  3450. var charSpacing = current.charSpacing;
  3451. var wordSpacing = current.wordSpacing;
  3452. var fontDirection = current.fontDirection;
  3453. var textHScale = current.textHScale * fontDirection;
  3454. var glyphsLength = glyphs.length;
  3455. var vertical = font.vertical;
  3456. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3457. var x = 0, i;
  3458. for (i = 0; i < glyphsLength; ++i) {
  3459. var glyph = glyphs[i];
  3460. if (glyph === null) {
  3461. // word break
  3462. x += fontDirection * wordSpacing;
  3463. continue;
  3464. } else if (isNum(glyph)) {
  3465. x += -glyph * fontSize * 0.001;
  3466. continue;
  3467. }
  3468. current.xcoords.push(current.x + x * textHScale);
  3469. var width = glyph.width;
  3470. var character = glyph.fontChar;
  3471. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3472. x += charWidth;
  3473. current.tspan.textContent += character;
  3474. }
  3475. if (vertical) {
  3476. current.y -= x * textHScale;
  3477. } else {
  3478. current.x += x * textHScale;
  3479. }
  3480. current.tspan.setAttributeNS(null, 'x',
  3481. current.xcoords.map(pf).join(' '));
  3482. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3483. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3484. current.tspan.setAttributeNS(null, 'font-size',
  3485. pf(current.fontSize) + 'px');
  3486. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3487. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3488. }
  3489. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3490. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3491. }
  3492. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3493. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3494. }
  3495. current.txtElement.setAttributeNS(null, 'transform',
  3496. pm(current.textMatrix) +
  3497. ' scale(1, -1)' );
  3498. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3499. current.txtElement.appendChild(current.tspan);
  3500. current.txtgrp.appendChild(current.txtElement);
  3501. this.tgrp.appendChild(current.txtElement);
  3502. },
  3503. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3504. this.setLeading(-y);
  3505. this.moveText(x, y);
  3506. },
  3507. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3508. if (!this.cssStyle) {
  3509. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3510. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3511. this.defs.appendChild(this.cssStyle);
  3512. }
  3513. var url = createObjectURL(fontObj.data, fontObj.mimetype,
  3514. this.forceDataSchema);
  3515. this.cssStyle.textContent +=
  3516. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  3517. ' src: url(' + url + '); }\n';
  3518. },
  3519. setFont: function SVGGraphics_setFont(details) {
  3520. var current = this.current;
  3521. var fontObj = this.commonObjs.get(details[0]);
  3522. var size = details[1];
  3523. this.current.font = fontObj;
  3524. if (this.embedFonts && fontObj.data &&
  3525. !this.embeddedFonts[fontObj.loadedName]) {
  3526. this.addFontStyle(fontObj);
  3527. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3528. }
  3529. current.fontMatrix = (fontObj.fontMatrix ?
  3530. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3531. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3532. (fontObj.bold ? 'bold' : 'normal');
  3533. var italic = fontObj.italic ? 'italic' : 'normal';
  3534. if (size < 0) {
  3535. size = -size;
  3536. current.fontDirection = -1;
  3537. } else {
  3538. current.fontDirection = 1;
  3539. }
  3540. current.fontSize = size;
  3541. current.fontFamily = fontObj.loadedName;
  3542. current.fontWeight = bold;
  3543. current.fontStyle = italic;
  3544. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3545. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3546. current.xcoords = [];
  3547. },
  3548. endText: function SVGGraphics_endText() {
  3549. if (this.current.pendingClip) {
  3550. this.cgrp.appendChild(this.tgrp);
  3551. this.pgrp.appendChild(this.cgrp);
  3552. } else {
  3553. this.pgrp.appendChild(this.tgrp);
  3554. }
  3555. this.tgrp = document.createElementNS(NS, 'svg:g');
  3556. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3557. },
  3558. // Path properties
  3559. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3560. this.current.lineWidth = width;
  3561. },
  3562. setLineCap: function SVGGraphics_setLineCap(style) {
  3563. this.current.lineCap = LINE_CAP_STYLES[style];
  3564. },
  3565. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3566. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3567. },
  3568. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3569. this.current.miterLimit = limit;
  3570. },
  3571. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3572. var color = Util.makeCssRgb(r, g, b);
  3573. this.current.strokeColor = color;
  3574. },
  3575. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3576. var color = Util.makeCssRgb(r, g, b);
  3577. this.current.fillColor = color;
  3578. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3579. this.current.xcoords = [];
  3580. },
  3581. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3582. this.current.dashArray = dashArray;
  3583. this.current.dashPhase = dashPhase;
  3584. },
  3585. constructPath: function SVGGraphics_constructPath(ops, args) {
  3586. var current = this.current;
  3587. var x = current.x, y = current.y;
  3588. current.path = document.createElementNS(NS, 'svg:path');
  3589. var d = [];
  3590. var opLength = ops.length;
  3591. for (var i = 0, j = 0; i < opLength; i++) {
  3592. switch (ops[i] | 0) {
  3593. case OPS.rectangle:
  3594. x = args[j++];
  3595. y = args[j++];
  3596. var width = args[j++];
  3597. var height = args[j++];
  3598. var xw = x + width;
  3599. var yh = y + height;
  3600. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  3601. 'L', pf(x), pf(yh), 'Z');
  3602. break;
  3603. case OPS.moveTo:
  3604. x = args[j++];
  3605. y = args[j++];
  3606. d.push('M', pf(x), pf(y));
  3607. break;
  3608. case OPS.lineTo:
  3609. x = args[j++];
  3610. y = args[j++];
  3611. d.push('L', pf(x) , pf(y));
  3612. break;
  3613. case OPS.curveTo:
  3614. x = args[j + 4];
  3615. y = args[j + 5];
  3616. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  3617. pf(args[j + 3]), pf(x), pf(y));
  3618. j += 6;
  3619. break;
  3620. case OPS.curveTo2:
  3621. x = args[j + 2];
  3622. y = args[j + 3];
  3623. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  3624. pf(args[j + 2]), pf(args[j + 3]));
  3625. j += 4;
  3626. break;
  3627. case OPS.curveTo3:
  3628. x = args[j + 2];
  3629. y = args[j + 3];
  3630. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  3631. pf(x), pf(y));
  3632. j += 4;
  3633. break;
  3634. case OPS.closePath:
  3635. d.push('Z');
  3636. break;
  3637. }
  3638. }
  3639. current.path.setAttributeNS(null, 'd', d.join(' '));
  3640. current.path.setAttributeNS(null, 'stroke-miterlimit',
  3641. pf(current.miterLimit));
  3642. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3643. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3644. current.path.setAttributeNS(null, 'stroke-width',
  3645. pf(current.lineWidth) + 'px');
  3646. current.path.setAttributeNS(null, 'stroke-dasharray',
  3647. current.dashArray.map(pf).join(' '));
  3648. current.path.setAttributeNS(null, 'stroke-dashoffset',
  3649. pf(current.dashPhase) + 'px');
  3650. current.path.setAttributeNS(null, 'fill', 'none');
  3651. this.tgrp.appendChild(current.path);
  3652. if (current.pendingClip) {
  3653. this.cgrp.appendChild(this.tgrp);
  3654. this.pgrp.appendChild(this.cgrp);
  3655. } else {
  3656. this.pgrp.appendChild(this.tgrp);
  3657. }
  3658. // Saving a reference in current.element so that it can be addressed
  3659. // in 'fill' and 'stroke'
  3660. current.element = current.path;
  3661. current.setCurrentPoint(x, y);
  3662. },
  3663. endPath: function SVGGraphics_endPath() {
  3664. var current = this.current;
  3665. if (current.pendingClip) {
  3666. this.cgrp.appendChild(this.tgrp);
  3667. this.pgrp.appendChild(this.cgrp);
  3668. } else {
  3669. this.pgrp.appendChild(this.tgrp);
  3670. }
  3671. this.tgrp = document.createElementNS(NS, 'svg:g');
  3672. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3673. },
  3674. clip: function SVGGraphics_clip(type) {
  3675. var current = this.current;
  3676. // Add current path to clipping path
  3677. current.clipId = 'clippath' + clipCount;
  3678. clipCount++;
  3679. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3680. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3681. var clipElement = current.element.cloneNode();
  3682. if (type === 'evenodd') {
  3683. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3684. } else {
  3685. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3686. }
  3687. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3688. this.clippath.appendChild(clipElement);
  3689. this.defs.appendChild(this.clippath);
  3690. // Create a new group with that attribute
  3691. current.pendingClip = true;
  3692. this.cgrp = document.createElementNS(NS, 'svg:g');
  3693. this.cgrp.setAttributeNS(null, 'clip-path',
  3694. 'url(#' + current.clipId + ')');
  3695. this.pgrp.appendChild(this.cgrp);
  3696. },
  3697. closePath: function SVGGraphics_closePath() {
  3698. var current = this.current;
  3699. var d = current.path.getAttributeNS(null, 'd');
  3700. d += 'Z';
  3701. current.path.setAttributeNS(null, 'd', d);
  3702. },
  3703. setLeading: function SVGGraphics_setLeading(leading) {
  3704. this.current.leading = -leading;
  3705. },
  3706. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3707. this.current.textRise = textRise;
  3708. },
  3709. setHScale: function SVGGraphics_setHScale(scale) {
  3710. this.current.textHScale = scale / 100;
  3711. },
  3712. setGState: function SVGGraphics_setGState(states) {
  3713. for (var i = 0, ii = states.length; i < ii; i++) {
  3714. var state = states[i];
  3715. var key = state[0];
  3716. var value = state[1];
  3717. switch (key) {
  3718. case 'LW':
  3719. this.setLineWidth(value);
  3720. break;
  3721. case 'LC':
  3722. this.setLineCap(value);
  3723. break;
  3724. case 'LJ':
  3725. this.setLineJoin(value);
  3726. break;
  3727. case 'ML':
  3728. this.setMiterLimit(value);
  3729. break;
  3730. case 'D':
  3731. this.setDash(value[0], value[1]);
  3732. break;
  3733. case 'RI':
  3734. break;
  3735. case 'FL':
  3736. break;
  3737. case 'Font':
  3738. this.setFont(value);
  3739. break;
  3740. case 'CA':
  3741. break;
  3742. case 'ca':
  3743. break;
  3744. case 'BM':
  3745. break;
  3746. case 'SMask':
  3747. break;
  3748. }
  3749. }
  3750. },
  3751. fill: function SVGGraphics_fill() {
  3752. var current = this.current;
  3753. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3754. },
  3755. stroke: function SVGGraphics_stroke() {
  3756. var current = this.current;
  3757. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3758. current.element.setAttributeNS(null, 'fill', 'none');
  3759. },
  3760. eoFill: function SVGGraphics_eoFill() {
  3761. var current = this.current;
  3762. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3763. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3764. },
  3765. fillStroke: function SVGGraphics_fillStroke() {
  3766. // Order is important since stroke wants fill to be none.
  3767. // First stroke, then if fill needed, it will be overwritten.
  3768. this.stroke();
  3769. this.fill();
  3770. },
  3771. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3772. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3773. this.fillStroke();
  3774. },
  3775. closeStroke: function SVGGraphics_closeStroke() {
  3776. this.closePath();
  3777. this.stroke();
  3778. },
  3779. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3780. this.closePath();
  3781. this.fillStroke();
  3782. },
  3783. paintSolidColorImageMask:
  3784. function SVGGraphics_paintSolidColorImageMask() {
  3785. var current = this.current;
  3786. var rect = document.createElementNS(NS, 'svg:rect');
  3787. rect.setAttributeNS(null, 'x', '0');
  3788. rect.setAttributeNS(null, 'y', '0');
  3789. rect.setAttributeNS(null, 'width', '1px');
  3790. rect.setAttributeNS(null, 'height', '1px');
  3791. rect.setAttributeNS(null, 'fill', current.fillColor);
  3792. this.tgrp.appendChild(rect);
  3793. },
  3794. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3795. var current = this.current;
  3796. var imgObj = this.objs.get(objId);
  3797. var imgEl = document.createElementNS(NS, 'svg:image');
  3798. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3799. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3800. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3801. imgEl.setAttributeNS(null, 'x', '0');
  3802. imgEl.setAttributeNS(null, 'y', pf(-h));
  3803. imgEl.setAttributeNS(null, 'transform',
  3804. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3805. this.tgrp.appendChild(imgEl);
  3806. if (current.pendingClip) {
  3807. this.cgrp.appendChild(this.tgrp);
  3808. this.pgrp.appendChild(this.cgrp);
  3809. } else {
  3810. this.pgrp.appendChild(this.tgrp);
  3811. }
  3812. },
  3813. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3814. var imgData = this.objs.get(objId);
  3815. if (!imgData) {
  3816. warn('Dependent image isn\'t ready yet');
  3817. return;
  3818. }
  3819. this.paintInlineImageXObject(imgData);
  3820. },
  3821. paintInlineImageXObject:
  3822. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3823. var current = this.current;
  3824. var width = imgData.width;
  3825. var height = imgData.height;
  3826. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3827. var cliprect = document.createElementNS(NS, 'svg:rect');
  3828. cliprect.setAttributeNS(null, 'x', '0');
  3829. cliprect.setAttributeNS(null, 'y', '0');
  3830. cliprect.setAttributeNS(null, 'width', pf(width));
  3831. cliprect.setAttributeNS(null, 'height', pf(height));
  3832. current.element = cliprect;
  3833. this.clip('nonzero');
  3834. var imgEl = document.createElementNS(NS, 'svg:image');
  3835. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  3836. imgEl.setAttributeNS(null, 'x', '0');
  3837. imgEl.setAttributeNS(null, 'y', pf(-height));
  3838. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  3839. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  3840. imgEl.setAttributeNS(null, 'transform',
  3841. 'scale(' + pf(1 / width) + ' ' +
  3842. pf(-1 / height) + ')');
  3843. if (mask) {
  3844. mask.appendChild(imgEl);
  3845. } else {
  3846. this.tgrp.appendChild(imgEl);
  3847. }
  3848. if (current.pendingClip) {
  3849. this.cgrp.appendChild(this.tgrp);
  3850. this.pgrp.appendChild(this.cgrp);
  3851. } else {
  3852. this.pgrp.appendChild(this.tgrp);
  3853. }
  3854. },
  3855. paintImageMaskXObject:
  3856. function SVGGraphics_paintImageMaskXObject(imgData) {
  3857. var current = this.current;
  3858. var width = imgData.width;
  3859. var height = imgData.height;
  3860. var fillColor = current.fillColor;
  3861. current.maskId = 'mask' + maskCount++;
  3862. var mask = document.createElementNS(NS, 'svg:mask');
  3863. mask.setAttributeNS(null, 'id', current.maskId);
  3864. var rect = document.createElementNS(NS, 'svg:rect');
  3865. rect.setAttributeNS(null, 'x', '0');
  3866. rect.setAttributeNS(null, 'y', '0');
  3867. rect.setAttributeNS(null, 'width', pf(width));
  3868. rect.setAttributeNS(null, 'height', pf(height));
  3869. rect.setAttributeNS(null, 'fill', fillColor);
  3870. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  3871. this.defs.appendChild(mask);
  3872. this.tgrp.appendChild(rect);
  3873. this.paintInlineImageXObject(imgData, mask);
  3874. },
  3875. paintFormXObjectBegin:
  3876. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  3877. this.save();
  3878. if (isArray(matrix) && matrix.length === 6) {
  3879. this.transform(matrix[0], matrix[1], matrix[2],
  3880. matrix[3], matrix[4], matrix[5]);
  3881. }
  3882. if (isArray(bbox) && bbox.length === 4) {
  3883. var width = bbox[2] - bbox[0];
  3884. var height = bbox[3] - bbox[1];
  3885. var cliprect = document.createElementNS(NS, 'svg:rect');
  3886. cliprect.setAttributeNS(null, 'x', bbox[0]);
  3887. cliprect.setAttributeNS(null, 'y', bbox[1]);
  3888. cliprect.setAttributeNS(null, 'width', pf(width));
  3889. cliprect.setAttributeNS(null, 'height', pf(height));
  3890. this.current.element = cliprect;
  3891. this.clip('nonzero');
  3892. this.endPath();
  3893. }
  3894. },
  3895. paintFormXObjectEnd:
  3896. function SVGGraphics_paintFormXObjectEnd() {
  3897. this.restore();
  3898. }
  3899. };
  3900. return SVGGraphics;
  3901. })();
  3902. exports.SVGGraphics = SVGGraphics;
  3903. }));
  3904. (function (root, factory) {
  3905. {
  3906. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  3907. root.pdfjsDisplayDOMUtils);
  3908. }
  3909. }(this, function (exports, sharedUtil, displayDOMUtils) {
  3910. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  3911. var AnnotationType = sharedUtil.AnnotationType;
  3912. var Util = sharedUtil.Util;
  3913. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  3914. var LinkTarget = displayDOMUtils.LinkTarget;
  3915. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  3916. var warn = sharedUtil.warn;
  3917. var CustomStyle = displayDOMUtils.CustomStyle;
  3918. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  3919. /**
  3920. * @typedef {Object} AnnotationElementParameters
  3921. * @property {Object} data
  3922. * @property {HTMLDivElement} layer
  3923. * @property {PDFPage} page
  3924. * @property {PageViewport} viewport
  3925. * @property {IPDFLinkService} linkService
  3926. * @property {DownloadManager} downloadManager
  3927. * @property {string} imageResourcesPath
  3928. * @property {boolean} renderInteractiveForms
  3929. */
  3930. /**
  3931. * @class
  3932. * @alias AnnotationElementFactory
  3933. */
  3934. function AnnotationElementFactory() {}
  3935. AnnotationElementFactory.prototype =
  3936. /** @lends AnnotationElementFactory.prototype */ {
  3937. /**
  3938. * @param {AnnotationElementParameters} parameters
  3939. * @returns {AnnotationElement}
  3940. */
  3941. create: function AnnotationElementFactory_create(parameters) {
  3942. var subtype = parameters.data.annotationType;
  3943. switch (subtype) {
  3944. case AnnotationType.LINK:
  3945. return new LinkAnnotationElement(parameters);
  3946. case AnnotationType.TEXT:
  3947. return new TextAnnotationElement(parameters);
  3948. case AnnotationType.WIDGET:
  3949. var fieldType = parameters.data.fieldType;
  3950. switch (fieldType) {
  3951. case 'Tx':
  3952. return new TextWidgetAnnotationElement(parameters);
  3953. case 'Ch':
  3954. return new ChoiceWidgetAnnotationElement(parameters);
  3955. }
  3956. return new WidgetAnnotationElement(parameters);
  3957. case AnnotationType.POPUP:
  3958. return new PopupAnnotationElement(parameters);
  3959. case AnnotationType.HIGHLIGHT:
  3960. return new HighlightAnnotationElement(parameters);
  3961. case AnnotationType.UNDERLINE:
  3962. return new UnderlineAnnotationElement(parameters);
  3963. case AnnotationType.SQUIGGLY:
  3964. return new SquigglyAnnotationElement(parameters);
  3965. case AnnotationType.STRIKEOUT:
  3966. return new StrikeOutAnnotationElement(parameters);
  3967. case AnnotationType.FILEATTACHMENT:
  3968. return new FileAttachmentAnnotationElement(parameters);
  3969. default:
  3970. return new AnnotationElement(parameters);
  3971. }
  3972. }
  3973. };
  3974. /**
  3975. * @class
  3976. * @alias AnnotationElement
  3977. */
  3978. var AnnotationElement = (function AnnotationElementClosure() {
  3979. function AnnotationElement(parameters, isRenderable) {
  3980. this.isRenderable = isRenderable || false;
  3981. this.data = parameters.data;
  3982. this.layer = parameters.layer;
  3983. this.page = parameters.page;
  3984. this.viewport = parameters.viewport;
  3985. this.linkService = parameters.linkService;
  3986. this.downloadManager = parameters.downloadManager;
  3987. this.imageResourcesPath = parameters.imageResourcesPath;
  3988. this.renderInteractiveForms = parameters.renderInteractiveForms;
  3989. if (isRenderable) {
  3990. this.container = this._createContainer();
  3991. }
  3992. }
  3993. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  3994. /**
  3995. * Create an empty container for the annotation's HTML element.
  3996. *
  3997. * @private
  3998. * @memberof AnnotationElement
  3999. * @returns {HTMLSectionElement}
  4000. */
  4001. _createContainer: function AnnotationElement_createContainer() {
  4002. var data = this.data, page = this.page, viewport = this.viewport;
  4003. var container = document.createElement('section');
  4004. var width = data.rect[2] - data.rect[0];
  4005. var height = data.rect[3] - data.rect[1];
  4006. container.setAttribute('data-annotation-id', data.id);
  4007. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4008. // position on subsequent calls to `_createContainer` (see issue 6804).
  4009. var rect = Util.normalizeRect([
  4010. data.rect[0],
  4011. page.view[3] - data.rect[1] + page.view[1],
  4012. data.rect[2],
  4013. page.view[3] - data.rect[3] + page.view[1]
  4014. ]);
  4015. CustomStyle.setProp('transform', container,
  4016. 'matrix(' + viewport.transform.join(',') + ')');
  4017. CustomStyle.setProp('transformOrigin', container,
  4018. -rect[0] + 'px ' + -rect[1] + 'px');
  4019. if (data.borderStyle.width > 0) {
  4020. container.style.borderWidth = data.borderStyle.width + 'px';
  4021. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4022. // Underline styles only have a bottom border, so we do not need
  4023. // to adjust for all borders. This yields a similar result as
  4024. // Adobe Acrobat/Reader.
  4025. width = width - 2 * data.borderStyle.width;
  4026. height = height - 2 * data.borderStyle.width;
  4027. }
  4028. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4029. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4030. if (horizontalRadius > 0 || verticalRadius > 0) {
  4031. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4032. CustomStyle.setProp('borderRadius', container, radius);
  4033. }
  4034. switch (data.borderStyle.style) {
  4035. case AnnotationBorderStyleType.SOLID:
  4036. container.style.borderStyle = 'solid';
  4037. break;
  4038. case AnnotationBorderStyleType.DASHED:
  4039. container.style.borderStyle = 'dashed';
  4040. break;
  4041. case AnnotationBorderStyleType.BEVELED:
  4042. warn('Unimplemented border style: beveled');
  4043. break;
  4044. case AnnotationBorderStyleType.INSET:
  4045. warn('Unimplemented border style: inset');
  4046. break;
  4047. case AnnotationBorderStyleType.UNDERLINE:
  4048. container.style.borderBottomStyle = 'solid';
  4049. break;
  4050. default:
  4051. break;
  4052. }
  4053. if (data.color) {
  4054. container.style.borderColor =
  4055. Util.makeCssRgb(data.color[0] | 0,
  4056. data.color[1] | 0,
  4057. data.color[2] | 0);
  4058. } else {
  4059. // Transparent (invisible) border, so do not draw it at all.
  4060. container.style.borderWidth = 0;
  4061. }
  4062. }
  4063. container.style.left = rect[0] + 'px';
  4064. container.style.top = rect[1] + 'px';
  4065. container.style.width = width + 'px';
  4066. container.style.height = height + 'px';
  4067. return container;
  4068. },
  4069. /**
  4070. * Create a popup for the annotation's HTML element. This is used for
  4071. * annotations that do not have a Popup entry in the dictionary, but
  4072. * are of a type that works with popups (such as Highlight annotations).
  4073. *
  4074. * @private
  4075. * @param {HTMLSectionElement} container
  4076. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4077. * @param {Object} data
  4078. * @memberof AnnotationElement
  4079. */
  4080. _createPopup:
  4081. function AnnotationElement_createPopup(container, trigger, data) {
  4082. // If no trigger element is specified, create it.
  4083. if (!trigger) {
  4084. trigger = document.createElement('div');
  4085. trigger.style.height = container.style.height;
  4086. trigger.style.width = container.style.width;
  4087. container.appendChild(trigger);
  4088. }
  4089. var popupElement = new PopupElement({
  4090. container: container,
  4091. trigger: trigger,
  4092. color: data.color,
  4093. title: data.title,
  4094. contents: data.contents,
  4095. hideWrapper: true
  4096. });
  4097. var popup = popupElement.render();
  4098. // Position the popup next to the annotation's container.
  4099. popup.style.left = container.style.width;
  4100. container.appendChild(popup);
  4101. },
  4102. /**
  4103. * Render the annotation's HTML element in the empty container.
  4104. *
  4105. * @public
  4106. * @memberof AnnotationElement
  4107. */
  4108. render: function AnnotationElement_render() {
  4109. throw new Error('Abstract method AnnotationElement.render called');
  4110. }
  4111. };
  4112. return AnnotationElement;
  4113. })();
  4114. /**
  4115. * @class
  4116. * @alias LinkAnnotationElement
  4117. */
  4118. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  4119. function LinkAnnotationElement(parameters) {
  4120. AnnotationElement.call(this, parameters, true);
  4121. }
  4122. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4123. /**
  4124. * Render the link annotation's HTML element in the empty container.
  4125. *
  4126. * @public
  4127. * @memberof LinkAnnotationElement
  4128. * @returns {HTMLSectionElement}
  4129. */
  4130. render: function LinkAnnotationElement_render() {
  4131. this.container.className = 'linkAnnotation';
  4132. var link = document.createElement('a');
  4133. addLinkAttributes(link, {
  4134. url: this.data.url,
  4135. target: (this.data.newWindow ? LinkTarget.BLANK : undefined),
  4136. });
  4137. if (!this.data.url) {
  4138. if (this.data.action) {
  4139. this._bindNamedAction(link, this.data.action);
  4140. } else {
  4141. this._bindLink(link, (this.data.dest || null));
  4142. }
  4143. }
  4144. this.container.appendChild(link);
  4145. return this.container;
  4146. },
  4147. /**
  4148. * Bind internal links to the link element.
  4149. *
  4150. * @private
  4151. * @param {Object} link
  4152. * @param {Object} destination
  4153. * @memberof LinkAnnotationElement
  4154. */
  4155. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4156. var self = this;
  4157. link.href = this.linkService.getDestinationHash(destination);
  4158. link.onclick = function() {
  4159. if (destination) {
  4160. self.linkService.navigateTo(destination);
  4161. }
  4162. return false;
  4163. };
  4164. if (destination) {
  4165. link.className = 'internalLink';
  4166. }
  4167. },
  4168. /**
  4169. * Bind named actions to the link element.
  4170. *
  4171. * @private
  4172. * @param {Object} link
  4173. * @param {Object} action
  4174. * @memberof LinkAnnotationElement
  4175. */
  4176. _bindNamedAction:
  4177. function LinkAnnotationElement_bindNamedAction(link, action) {
  4178. var self = this;
  4179. link.href = this.linkService.getAnchorUrl('');
  4180. link.onclick = function() {
  4181. self.linkService.executeNamedAction(action);
  4182. return false;
  4183. };
  4184. link.className = 'internalLink';
  4185. }
  4186. });
  4187. return LinkAnnotationElement;
  4188. })();
  4189. /**
  4190. * @class
  4191. * @alias TextAnnotationElement
  4192. */
  4193. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  4194. function TextAnnotationElement(parameters) {
  4195. var isRenderable = !!(parameters.data.hasPopup ||
  4196. parameters.data.title || parameters.data.contents);
  4197. AnnotationElement.call(this, parameters, isRenderable);
  4198. }
  4199. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4200. /**
  4201. * Render the text annotation's HTML element in the empty container.
  4202. *
  4203. * @public
  4204. * @memberof TextAnnotationElement
  4205. * @returns {HTMLSectionElement}
  4206. */
  4207. render: function TextAnnotationElement_render() {
  4208. this.container.className = 'textAnnotation';
  4209. var image = document.createElement('img');
  4210. image.style.height = this.container.style.height;
  4211. image.style.width = this.container.style.width;
  4212. image.src = this.imageResourcesPath + 'annotation-' +
  4213. this.data.name.toLowerCase() + '.svg';
  4214. image.alt = '[{{type}} Annotation]';
  4215. image.dataset.l10nId = 'text_annotation_type';
  4216. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  4217. if (!this.data.hasPopup) {
  4218. this._createPopup(this.container, image, this.data);
  4219. }
  4220. this.container.appendChild(image);
  4221. return this.container;
  4222. }
  4223. });
  4224. return TextAnnotationElement;
  4225. })();
  4226. /**
  4227. * @class
  4228. * @alias WidgetAnnotationElement
  4229. */
  4230. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  4231. function WidgetAnnotationElement(parameters, isRenderable) {
  4232. AnnotationElement.call(this, parameters, isRenderable);
  4233. }
  4234. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4235. /**
  4236. * Render the widget annotation's HTML element in the empty container.
  4237. *
  4238. * @public
  4239. * @memberof WidgetAnnotationElement
  4240. * @returns {HTMLSectionElement}
  4241. */
  4242. render: function WidgetAnnotationElement_render() {
  4243. // Show only the container for unsupported field types.
  4244. return this.container;
  4245. }
  4246. });
  4247. return WidgetAnnotationElement;
  4248. })();
  4249. /**
  4250. * @class
  4251. * @alias TextWidgetAnnotationElement
  4252. */
  4253. var TextWidgetAnnotationElement = (
  4254. function TextWidgetAnnotationElementClosure() {
  4255. var TEXT_ALIGNMENT = ['left', 'center', 'right'];
  4256. function TextWidgetAnnotationElement(parameters) {
  4257. var isRenderable = parameters.renderInteractiveForms ||
  4258. (!parameters.data.hasAppearance && !!parameters.data.fieldValue);
  4259. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4260. }
  4261. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4262. /**
  4263. * Render the text widget annotation's HTML element in the empty container.
  4264. *
  4265. * @public
  4266. * @memberof TextWidgetAnnotationElement
  4267. * @returns {HTMLSectionElement}
  4268. */
  4269. render: function TextWidgetAnnotationElement_render() {
  4270. this.container.className = 'textWidgetAnnotation';
  4271. var element = null;
  4272. if (this.renderInteractiveForms) {
  4273. // NOTE: We cannot set the values using `element.value` below, since it
  4274. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4275. // from parsing the elements correctly for the reference tests.
  4276. if (this.data.multiLine) {
  4277. element = document.createElement('textarea');
  4278. element.textContent = this.data.fieldValue;
  4279. } else {
  4280. element = document.createElement('input');
  4281. element.type = 'text';
  4282. element.setAttribute('value', this.data.fieldValue);
  4283. }
  4284. element.disabled = this.data.readOnly;
  4285. if (this.data.maxLen !== null) {
  4286. element.maxLength = this.data.maxLen;
  4287. }
  4288. if (this.data.comb) {
  4289. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4290. var combWidth = fieldWidth / this.data.maxLen;
  4291. element.classList.add('comb');
  4292. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4293. }
  4294. } else {
  4295. element = document.createElement('div');
  4296. element.textContent = this.data.fieldValue;
  4297. element.style.verticalAlign = 'middle';
  4298. element.style.display = 'table-cell';
  4299. var font = null;
  4300. if (this.data.fontRefName) {
  4301. font = this.page.commonObjs.getData(this.data.fontRefName);
  4302. }
  4303. this._setTextStyle(element, font);
  4304. }
  4305. if (this.data.textAlignment !== null) {
  4306. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4307. }
  4308. this.container.appendChild(element);
  4309. return this.container;
  4310. },
  4311. /**
  4312. * Apply text styles to the text in the element.
  4313. *
  4314. * @private
  4315. * @param {HTMLDivElement} element
  4316. * @param {Object} font
  4317. * @memberof TextWidgetAnnotationElement
  4318. */
  4319. _setTextStyle:
  4320. function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4321. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4322. var style = element.style;
  4323. style.fontSize = this.data.fontSize + 'px';
  4324. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  4325. if (!font) {
  4326. return;
  4327. }
  4328. style.fontWeight = (font.black ?
  4329. (font.bold ? '900' : 'bold') :
  4330. (font.bold ? 'bold' : 'normal'));
  4331. style.fontStyle = (font.italic ? 'italic' : 'normal');
  4332. // Use a reasonable default font if the font doesn't specify a fallback.
  4333. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4334. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4335. style.fontFamily = fontFamily + fallbackName;
  4336. }
  4337. });
  4338. return TextWidgetAnnotationElement;
  4339. })();
  4340. /**
  4341. * @class
  4342. * @alias ChoiceWidgetAnnotationElement
  4343. */
  4344. var ChoiceWidgetAnnotationElement = (
  4345. function ChoiceWidgetAnnotationElementClosure() {
  4346. function ChoiceWidgetAnnotationElement(parameters) {
  4347. WidgetAnnotationElement.call(this, parameters,
  4348. parameters.renderInteractiveForms);
  4349. }
  4350. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4351. /**
  4352. * Render the choice widget annotation's HTML element in the empty
  4353. * container.
  4354. *
  4355. * @public
  4356. * @memberof ChoiceWidgetAnnotationElement
  4357. * @returns {HTMLSectionElement}
  4358. */
  4359. render: function ChoiceWidgetAnnotationElement_render() {
  4360. this.container.className = 'choiceWidgetAnnotation';
  4361. var selectElement = document.createElement('select');
  4362. selectElement.disabled = this.data.readOnly;
  4363. if (!this.data.combo) {
  4364. // List boxes have a size and (optionally) multiple selection.
  4365. selectElement.size = this.data.options.length;
  4366. if (this.data.multiSelect) {
  4367. selectElement.multiple = true;
  4368. }
  4369. }
  4370. // Insert the options into the choice field.
  4371. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4372. var option = this.data.options[i];
  4373. var optionElement = document.createElement('option');
  4374. optionElement.textContent = option.displayValue;
  4375. optionElement.value = option.exportValue;
  4376. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4377. optionElement.setAttribute('selected', true);
  4378. }
  4379. selectElement.appendChild(optionElement);
  4380. }
  4381. this.container.appendChild(selectElement);
  4382. return this.container;
  4383. }
  4384. });
  4385. return ChoiceWidgetAnnotationElement;
  4386. })();
  4387. /**
  4388. * @class
  4389. * @alias PopupAnnotationElement
  4390. */
  4391. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  4392. function PopupAnnotationElement(parameters) {
  4393. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4394. AnnotationElement.call(this, parameters, isRenderable);
  4395. }
  4396. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4397. /**
  4398. * Render the popup annotation's HTML element in the empty container.
  4399. *
  4400. * @public
  4401. * @memberof PopupAnnotationElement
  4402. * @returns {HTMLSectionElement}
  4403. */
  4404. render: function PopupAnnotationElement_render() {
  4405. this.container.className = 'popupAnnotation';
  4406. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4407. var parentElement = this.layer.querySelector(selector);
  4408. if (!parentElement) {
  4409. return this.container;
  4410. }
  4411. var popup = new PopupElement({
  4412. container: this.container,
  4413. trigger: parentElement,
  4414. color: this.data.color,
  4415. title: this.data.title,
  4416. contents: this.data.contents
  4417. });
  4418. // Position the popup next to the parent annotation's container.
  4419. // PDF viewers ignore a popup annotation's rectangle.
  4420. var parentLeft = parseFloat(parentElement.style.left);
  4421. var parentWidth = parseFloat(parentElement.style.width);
  4422. CustomStyle.setProp('transformOrigin', this.container,
  4423. -(parentLeft + parentWidth) + 'px -' +
  4424. parentElement.style.top);
  4425. this.container.style.left = (parentLeft + parentWidth) + 'px';
  4426. this.container.appendChild(popup.render());
  4427. return this.container;
  4428. }
  4429. });
  4430. return PopupAnnotationElement;
  4431. })();
  4432. /**
  4433. * @class
  4434. * @alias PopupElement
  4435. */
  4436. var PopupElement = (function PopupElementClosure() {
  4437. var BACKGROUND_ENLIGHT = 0.7;
  4438. function PopupElement(parameters) {
  4439. this.container = parameters.container;
  4440. this.trigger = parameters.trigger;
  4441. this.color = parameters.color;
  4442. this.title = parameters.title;
  4443. this.contents = parameters.contents;
  4444. this.hideWrapper = parameters.hideWrapper || false;
  4445. this.pinned = false;
  4446. }
  4447. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  4448. /**
  4449. * Render the popup's HTML element.
  4450. *
  4451. * @public
  4452. * @memberof PopupElement
  4453. * @returns {HTMLSectionElement}
  4454. */
  4455. render: function PopupElement_render() {
  4456. var wrapper = document.createElement('div');
  4457. wrapper.className = 'popupWrapper';
  4458. // For Popup annotations we hide the entire section because it contains
  4459. // only the popup. However, for Text annotations without a separate Popup
  4460. // annotation, we cannot hide the entire container as the image would
  4461. // disappear too. In that special case, hiding the wrapper suffices.
  4462. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  4463. this.hideElement.setAttribute('hidden', true);
  4464. var popup = document.createElement('div');
  4465. popup.className = 'popup';
  4466. var color = this.color;
  4467. if (color) {
  4468. // Enlighten the color.
  4469. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4470. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4471. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4472. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4473. }
  4474. var contents = this._formatContents(this.contents);
  4475. var title = document.createElement('h1');
  4476. title.textContent = this.title;
  4477. // Attach the event listeners to the trigger element.
  4478. this.trigger.addEventListener('click', this._toggle.bind(this));
  4479. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4480. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4481. popup.addEventListener('click', this._hide.bind(this, true));
  4482. popup.appendChild(title);
  4483. popup.appendChild(contents);
  4484. wrapper.appendChild(popup);
  4485. return wrapper;
  4486. },
  4487. /**
  4488. * Format the contents of the popup by adding newlines where necessary.
  4489. *
  4490. * @private
  4491. * @param {string} contents
  4492. * @memberof PopupElement
  4493. * @returns {HTMLParagraphElement}
  4494. */
  4495. _formatContents: function PopupElement_formatContents(contents) {
  4496. var p = document.createElement('p');
  4497. var lines = contents.split(/(?:\r\n?|\n)/);
  4498. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4499. var line = lines[i];
  4500. p.appendChild(document.createTextNode(line));
  4501. if (i < (ii - 1)) {
  4502. p.appendChild(document.createElement('br'));
  4503. }
  4504. }
  4505. return p;
  4506. },
  4507. /**
  4508. * Toggle the visibility of the popup.
  4509. *
  4510. * @private
  4511. * @memberof PopupElement
  4512. */
  4513. _toggle: function PopupElement_toggle() {
  4514. if (this.pinned) {
  4515. this._hide(true);
  4516. } else {
  4517. this._show(true);
  4518. }
  4519. },
  4520. /**
  4521. * Show the popup.
  4522. *
  4523. * @private
  4524. * @param {boolean} pin
  4525. * @memberof PopupElement
  4526. */
  4527. _show: function PopupElement_show(pin) {
  4528. if (pin) {
  4529. this.pinned = true;
  4530. }
  4531. if (this.hideElement.hasAttribute('hidden')) {
  4532. this.hideElement.removeAttribute('hidden');
  4533. this.container.style.zIndex += 1;
  4534. }
  4535. },
  4536. /**
  4537. * Hide the popup.
  4538. *
  4539. * @private
  4540. * @param {boolean} unpin
  4541. * @memberof PopupElement
  4542. */
  4543. _hide: function PopupElement_hide(unpin) {
  4544. if (unpin) {
  4545. this.pinned = false;
  4546. }
  4547. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4548. this.hideElement.setAttribute('hidden', true);
  4549. this.container.style.zIndex -= 1;
  4550. }
  4551. }
  4552. };
  4553. return PopupElement;
  4554. })();
  4555. /**
  4556. * @class
  4557. * @alias HighlightAnnotationElement
  4558. */
  4559. var HighlightAnnotationElement = (
  4560. function HighlightAnnotationElementClosure() {
  4561. function HighlightAnnotationElement(parameters) {
  4562. var isRenderable = !!(parameters.data.hasPopup ||
  4563. parameters.data.title || parameters.data.contents);
  4564. AnnotationElement.call(this, parameters, isRenderable);
  4565. }
  4566. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4567. /**
  4568. * Render the highlight annotation's HTML element in the empty container.
  4569. *
  4570. * @public
  4571. * @memberof HighlightAnnotationElement
  4572. * @returns {HTMLSectionElement}
  4573. */
  4574. render: function HighlightAnnotationElement_render() {
  4575. this.container.className = 'highlightAnnotation';
  4576. if (!this.data.hasPopup) {
  4577. this._createPopup(this.container, null, this.data);
  4578. }
  4579. return this.container;
  4580. }
  4581. });
  4582. return HighlightAnnotationElement;
  4583. })();
  4584. /**
  4585. * @class
  4586. * @alias UnderlineAnnotationElement
  4587. */
  4588. var UnderlineAnnotationElement = (
  4589. function UnderlineAnnotationElementClosure() {
  4590. function UnderlineAnnotationElement(parameters) {
  4591. var isRenderable = !!(parameters.data.hasPopup ||
  4592. parameters.data.title || parameters.data.contents);
  4593. AnnotationElement.call(this, parameters, isRenderable);
  4594. }
  4595. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4596. /**
  4597. * Render the underline annotation's HTML element in the empty container.
  4598. *
  4599. * @public
  4600. * @memberof UnderlineAnnotationElement
  4601. * @returns {HTMLSectionElement}
  4602. */
  4603. render: function UnderlineAnnotationElement_render() {
  4604. this.container.className = 'underlineAnnotation';
  4605. if (!this.data.hasPopup) {
  4606. this._createPopup(this.container, null, this.data);
  4607. }
  4608. return this.container;
  4609. }
  4610. });
  4611. return UnderlineAnnotationElement;
  4612. })();
  4613. /**
  4614. * @class
  4615. * @alias SquigglyAnnotationElement
  4616. */
  4617. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  4618. function SquigglyAnnotationElement(parameters) {
  4619. var isRenderable = !!(parameters.data.hasPopup ||
  4620. parameters.data.title || parameters.data.contents);
  4621. AnnotationElement.call(this, parameters, isRenderable);
  4622. }
  4623. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4624. /**
  4625. * Render the squiggly annotation's HTML element in the empty container.
  4626. *
  4627. * @public
  4628. * @memberof SquigglyAnnotationElement
  4629. * @returns {HTMLSectionElement}
  4630. */
  4631. render: function SquigglyAnnotationElement_render() {
  4632. this.container.className = 'squigglyAnnotation';
  4633. if (!this.data.hasPopup) {
  4634. this._createPopup(this.container, null, this.data);
  4635. }
  4636. return this.container;
  4637. }
  4638. });
  4639. return SquigglyAnnotationElement;
  4640. })();
  4641. /**
  4642. * @class
  4643. * @alias StrikeOutAnnotationElement
  4644. */
  4645. var StrikeOutAnnotationElement = (
  4646. function StrikeOutAnnotationElementClosure() {
  4647. function StrikeOutAnnotationElement(parameters) {
  4648. var isRenderable = !!(parameters.data.hasPopup ||
  4649. parameters.data.title || parameters.data.contents);
  4650. AnnotationElement.call(this, parameters, isRenderable);
  4651. }
  4652. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4653. /**
  4654. * Render the strikeout annotation's HTML element in the empty container.
  4655. *
  4656. * @public
  4657. * @memberof StrikeOutAnnotationElement
  4658. * @returns {HTMLSectionElement}
  4659. */
  4660. render: function StrikeOutAnnotationElement_render() {
  4661. this.container.className = 'strikeoutAnnotation';
  4662. if (!this.data.hasPopup) {
  4663. this._createPopup(this.container, null, this.data);
  4664. }
  4665. return this.container;
  4666. }
  4667. });
  4668. return StrikeOutAnnotationElement;
  4669. })();
  4670. /**
  4671. * @class
  4672. * @alias FileAttachmentAnnotationElement
  4673. */
  4674. var FileAttachmentAnnotationElement = (
  4675. function FileAttachmentAnnotationElementClosure() {
  4676. function FileAttachmentAnnotationElement(parameters) {
  4677. AnnotationElement.call(this, parameters, true);
  4678. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4679. this.content = parameters.data.file.content;
  4680. }
  4681. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4682. /**
  4683. * Render the file attachment annotation's HTML element in the empty
  4684. * container.
  4685. *
  4686. * @public
  4687. * @memberof FileAttachmentAnnotationElement
  4688. * @returns {HTMLSectionElement}
  4689. */
  4690. render: function FileAttachmentAnnotationElement_render() {
  4691. this.container.className = 'fileAttachmentAnnotation';
  4692. var trigger = document.createElement('div');
  4693. trigger.style.height = this.container.style.height;
  4694. trigger.style.width = this.container.style.width;
  4695. trigger.addEventListener('dblclick', this._download.bind(this));
  4696. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4697. this._createPopup(this.container, trigger, this.data);
  4698. }
  4699. this.container.appendChild(trigger);
  4700. return this.container;
  4701. },
  4702. /**
  4703. * Download the file attachment associated with this annotation.
  4704. *
  4705. * @private
  4706. * @memberof FileAttachmentAnnotationElement
  4707. */
  4708. _download: function FileAttachmentAnnotationElement_download() {
  4709. if (!this.downloadManager) {
  4710. warn('Download cannot be started due to unavailable download manager');
  4711. return;
  4712. }
  4713. this.downloadManager.downloadData(this.content, this.filename, '');
  4714. }
  4715. });
  4716. return FileAttachmentAnnotationElement;
  4717. })();
  4718. /**
  4719. * @typedef {Object} AnnotationLayerParameters
  4720. * @property {PageViewport} viewport
  4721. * @property {HTMLDivElement} div
  4722. * @property {Array} annotations
  4723. * @property {PDFPage} page
  4724. * @property {IPDFLinkService} linkService
  4725. * @property {string} imageResourcesPath
  4726. * @property {boolean} renderInteractiveForms
  4727. */
  4728. /**
  4729. * @class
  4730. * @alias AnnotationLayer
  4731. */
  4732. var AnnotationLayer = (function AnnotationLayerClosure() {
  4733. return {
  4734. /**
  4735. * Render a new annotation layer with all annotation elements.
  4736. *
  4737. * @public
  4738. * @param {AnnotationLayerParameters} parameters
  4739. * @memberof AnnotationLayer
  4740. */
  4741. render: function AnnotationLayer_render(parameters) {
  4742. var annotationElementFactory = new AnnotationElementFactory();
  4743. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4744. var data = parameters.annotations[i];
  4745. if (!data) {
  4746. continue;
  4747. }
  4748. var properties = {
  4749. data: data,
  4750. layer: parameters.div,
  4751. page: parameters.page,
  4752. viewport: parameters.viewport,
  4753. linkService: parameters.linkService,
  4754. downloadManager: parameters.downloadManager,
  4755. imageResourcesPath: parameters.imageResourcesPath ||
  4756. getDefaultSetting('imageResourcesPath'),
  4757. renderInteractiveForms: parameters.renderInteractiveForms || false,
  4758. };
  4759. var element = annotationElementFactory.create(properties);
  4760. if (element.isRenderable) {
  4761. parameters.div.appendChild(element.render());
  4762. }
  4763. }
  4764. },
  4765. /**
  4766. * Update the annotation elements on existing annotation layer.
  4767. *
  4768. * @public
  4769. * @param {AnnotationLayerParameters} parameters
  4770. * @memberof AnnotationLayer
  4771. */
  4772. update: function AnnotationLayer_update(parameters) {
  4773. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4774. var data = parameters.annotations[i];
  4775. var element = parameters.div.querySelector(
  4776. '[data-annotation-id="' + data.id + '"]');
  4777. if (element) {
  4778. CustomStyle.setProp('transform', element,
  4779. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4780. }
  4781. }
  4782. parameters.div.removeAttribute('hidden');
  4783. }
  4784. };
  4785. })();
  4786. exports.AnnotationLayer = AnnotationLayer;
  4787. }));
  4788. (function (root, factory) {
  4789. {
  4790. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4791. root.pdfjsDisplayDOMUtils);
  4792. }
  4793. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4794. var Util = sharedUtil.Util;
  4795. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4796. var CustomStyle = displayDOMUtils.CustomStyle;
  4797. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4798. /**
  4799. * Text layer render parameters.
  4800. *
  4801. * @typedef {Object} TextLayerRenderParameters
  4802. * @property {TextContent} textContent - Text content to render (the object is
  4803. * returned by the page's getTextContent() method).
  4804. * @property {HTMLElement} container - HTML element that will contain text runs.
  4805. * @property {PageViewport} viewport - The target viewport to properly
  4806. * layout the text runs.
  4807. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4808. * the text items of the textContent input. This is output and shall be
  4809. * initially be set to empty array.
  4810. * @property {number} timeout - (optional) Delay in milliseconds before
  4811. * rendering of the text runs occurs.
  4812. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4813. * text selection enhancement.
  4814. */
  4815. var renderTextLayer = (function renderTextLayerClosure() {
  4816. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4817. var NonWhitespaceRegexp = /\S/;
  4818. function isAllWhitespace(str) {
  4819. return !NonWhitespaceRegexp.test(str);
  4820. }
  4821. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  4822. // creating many intermediate strings when building their 'style' properties.
  4823. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0,
  4824. 'px; font-family: ', '', ';'];
  4825. function appendText(task, geom, styles) {
  4826. // Initialize all used properties to keep the caches monomorphic.
  4827. var textDiv = document.createElement('div');
  4828. var textDivProperties = {
  4829. style: null,
  4830. angle: 0,
  4831. canvasWidth: 0,
  4832. isWhitespace: false,
  4833. originalTransform: null,
  4834. paddingBottom: 0,
  4835. paddingLeft: 0,
  4836. paddingRight: 0,
  4837. paddingTop: 0,
  4838. scale: 1,
  4839. };
  4840. task._textDivs.push(textDiv);
  4841. if (isAllWhitespace(geom.str)) {
  4842. textDivProperties.isWhitespace = true;
  4843. task._textDivProperties.set(textDiv, textDivProperties);
  4844. return;
  4845. }
  4846. var tx = Util.transform(task._viewport.transform, geom.transform);
  4847. var angle = Math.atan2(tx[1], tx[0]);
  4848. var style = styles[geom.fontName];
  4849. if (style.vertical) {
  4850. angle += Math.PI / 2;
  4851. }
  4852. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4853. var fontAscent = fontHeight;
  4854. if (style.ascent) {
  4855. fontAscent = style.ascent * fontAscent;
  4856. } else if (style.descent) {
  4857. fontAscent = (1 + style.descent) * fontAscent;
  4858. }
  4859. var left;
  4860. var top;
  4861. if (angle === 0) {
  4862. left = tx[4];
  4863. top = tx[5] - fontAscent;
  4864. } else {
  4865. left = tx[4] + (fontAscent * Math.sin(angle));
  4866. top = tx[5] - (fontAscent * Math.cos(angle));
  4867. }
  4868. styleBuf[1] = left;
  4869. styleBuf[3] = top;
  4870. styleBuf[5] = fontHeight;
  4871. styleBuf[7] = style.fontFamily;
  4872. textDivProperties.style = styleBuf.join('');
  4873. textDiv.setAttribute('style', textDivProperties.style);
  4874. textDiv.textContent = geom.str;
  4875. // |fontName| is only used by the Font Inspector. This test will succeed
  4876. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4877. // not worth the effort to do a more accurate test. We only use `dataset`
  4878. // here to make the font name available for the debugger.
  4879. if (getDefaultSetting('pdfBug')) {
  4880. textDiv.dataset.fontName = geom.fontName;
  4881. }
  4882. if (angle !== 0) {
  4883. textDivProperties.angle = angle * (180 / Math.PI);
  4884. }
  4885. // We don't bother scaling single-char text divs, because it has very
  4886. // little effect on text highlighting. This makes scrolling on docs with
  4887. // lots of such divs a lot faster.
  4888. if (geom.str.length > 1) {
  4889. if (style.vertical) {
  4890. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4891. } else {
  4892. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4893. }
  4894. }
  4895. task._textDivProperties.set(textDiv, textDivProperties);
  4896. if (task._enhanceTextSelection) {
  4897. var angleCos = 1, angleSin = 0;
  4898. if (angle !== 0) {
  4899. angleCos = Math.cos(angle);
  4900. angleSin = Math.sin(angle);
  4901. }
  4902. var divWidth = (style.vertical ? geom.height : geom.width) *
  4903. task._viewport.scale;
  4904. var divHeight = fontHeight;
  4905. var m, b;
  4906. if (angle !== 0) {
  4907. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  4908. b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  4909. } else {
  4910. b = [left, top, left + divWidth, top + divHeight];
  4911. }
  4912. task._bounds.push({
  4913. left: b[0],
  4914. top: b[1],
  4915. right: b[2],
  4916. bottom: b[3],
  4917. div: textDiv,
  4918. size: [divWidth, divHeight],
  4919. m: m
  4920. });
  4921. }
  4922. }
  4923. function render(task) {
  4924. if (task._canceled) {
  4925. return;
  4926. }
  4927. var textLayerFrag = task._container;
  4928. var textDivs = task._textDivs;
  4929. var capability = task._capability;
  4930. var textDivsLength = textDivs.length;
  4931. // No point in rendering many divs as it would make the browser
  4932. // unusable even after the divs are rendered.
  4933. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4934. task._renderingDone = true;
  4935. capability.resolve();
  4936. return;
  4937. }
  4938. var canvas = document.createElement('canvas');
  4939. canvas.mozOpaque = true;
  4940. var ctx = canvas.getContext('2d', {alpha: false});
  4941. var lastFontSize;
  4942. var lastFontFamily;
  4943. for (var i = 0; i < textDivsLength; i++) {
  4944. var textDiv = textDivs[i];
  4945. var textDivProperties = task._textDivProperties.get(textDiv);
  4946. if (textDivProperties.isWhitespace) {
  4947. continue;
  4948. }
  4949. var fontSize = textDiv.style.fontSize;
  4950. var fontFamily = textDiv.style.fontFamily;
  4951. // Only build font string and set to context if different from last.
  4952. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4953. ctx.font = fontSize + ' ' + fontFamily;
  4954. lastFontSize = fontSize;
  4955. lastFontFamily = fontFamily;
  4956. }
  4957. var width = ctx.measureText(textDiv.textContent).width;
  4958. textLayerFrag.appendChild(textDiv);
  4959. var transform = '';
  4960. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4961. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4962. transform = 'scaleX(' + textDivProperties.scale + ')';
  4963. }
  4964. if (textDivProperties.angle !== 0) {
  4965. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4966. }
  4967. if (transform !== '') {
  4968. textDivProperties.originalTransform = transform;
  4969. CustomStyle.setProp('transform', textDiv, transform);
  4970. }
  4971. task._textDivProperties.set(textDiv, textDivProperties);
  4972. }
  4973. task._renderingDone = true;
  4974. capability.resolve();
  4975. }
  4976. function expand(task) {
  4977. var bounds = task._bounds;
  4978. var viewport = task._viewport;
  4979. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4980. for (var i = 0; i < expanded.length; i++) {
  4981. var div = bounds[i].div;
  4982. var divProperties = task._textDivProperties.get(div);
  4983. if (divProperties.angle === 0) {
  4984. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4985. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4986. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4987. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4988. task._textDivProperties.set(div, divProperties);
  4989. continue;
  4990. }
  4991. // Box is rotated -- trying to find padding so rotated div will not
  4992. // exceed its expanded bounds.
  4993. var e = expanded[i], b = bounds[i];
  4994. var m = b.m, c = m[0], s = m[1];
  4995. // Finding intersections with expanded box.
  4996. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  4997. var ts = new Float64Array(64);
  4998. points.forEach(function (p, i) {
  4999. var t = Util.applyTransform(p, m);
  5000. ts[i + 0] = c && (e.left - t[0]) / c;
  5001. ts[i + 4] = s && (e.top - t[1]) / s;
  5002. ts[i + 8] = c && (e.right - t[0]) / c;
  5003. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5004. ts[i + 16] = s && (e.left - t[0]) / -s;
  5005. ts[i + 20] = c && (e.top - t[1]) / c;
  5006. ts[i + 24] = s && (e.right - t[0]) / -s;
  5007. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5008. ts[i + 32] = c && (e.left - t[0]) / -c;
  5009. ts[i + 36] = s && (e.top - t[1]) / -s;
  5010. ts[i + 40] = c && (e.right - t[0]) / -c;
  5011. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5012. ts[i + 48] = s && (e.left - t[0]) / s;
  5013. ts[i + 52] = c && (e.top - t[1]) / -c;
  5014. ts[i + 56] = s && (e.right - t[0]) / s;
  5015. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5016. });
  5017. var findPositiveMin = function (ts, offset, count) {
  5018. var result = 0;
  5019. for (var i = 0; i < count; i++) {
  5020. var t = ts[offset++];
  5021. if (t > 0) {
  5022. result = result ? Math.min(t, result) : t;
  5023. }
  5024. }
  5025. return result;
  5026. };
  5027. // Not based on math, but to simplify calculations, using cos and sin
  5028. // absolute values to not exceed the box (it can but insignificantly).
  5029. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5030. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5031. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5032. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5033. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5034. task._textDivProperties.set(div, divProperties);
  5035. }
  5036. }
  5037. function expandBounds(width, height, boxes) {
  5038. var bounds = boxes.map(function (box, i) {
  5039. return {
  5040. x1: box.left,
  5041. y1: box.top,
  5042. x2: box.right,
  5043. y2: box.bottom,
  5044. index: i,
  5045. x1New: undefined,
  5046. x2New: undefined
  5047. };
  5048. });
  5049. expandBoundsLTR(width, bounds);
  5050. var expanded = new Array(boxes.length);
  5051. bounds.forEach(function (b) {
  5052. var i = b.index;
  5053. expanded[i] = {
  5054. left: b.x1New,
  5055. top: 0,
  5056. right: b.x2New,
  5057. bottom: 0
  5058. };
  5059. });
  5060. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5061. // array and objects.
  5062. boxes.map(function (box, i) {
  5063. var e = expanded[i], b = bounds[i];
  5064. b.x1 = box.top;
  5065. b.y1 = width - e.right;
  5066. b.x2 = box.bottom;
  5067. b.y2 = width - e.left;
  5068. b.index = i;
  5069. b.x1New = undefined;
  5070. b.x2New = undefined;
  5071. });
  5072. expandBoundsLTR(height, bounds);
  5073. bounds.forEach(function (b) {
  5074. var i = b.index;
  5075. expanded[i].top = b.x1New;
  5076. expanded[i].bottom = b.x2New;
  5077. });
  5078. return expanded;
  5079. }
  5080. function expandBoundsLTR(width, bounds) {
  5081. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5082. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; });
  5083. // First we see on the horizon is a fake boundary.
  5084. var fakeBoundary = {
  5085. x1: -Infinity,
  5086. y1: -Infinity,
  5087. x2: 0,
  5088. y2: Infinity,
  5089. index: -1,
  5090. x1New: 0,
  5091. x2New: 0
  5092. };
  5093. var horizon = [{
  5094. start: -Infinity,
  5095. end: Infinity,
  5096. boundary: fakeBoundary
  5097. }];
  5098. bounds.forEach(function (boundary) {
  5099. // Searching for the affected part of horizon.
  5100. // TODO red-black tree or simple binary search
  5101. var i = 0;
  5102. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5103. i++;
  5104. }
  5105. var j = horizon.length - 1;
  5106. while(j >= 0 && horizon[j].start >= boundary.y2) {
  5107. j--;
  5108. }
  5109. var horizonPart, affectedBoundary;
  5110. var q, k, maxXNew = -Infinity;
  5111. for (q = i; q <= j; q++) {
  5112. horizonPart = horizon[q];
  5113. affectedBoundary = horizonPart.boundary;
  5114. var xNew;
  5115. if (affectedBoundary.x2 > boundary.x1) {
  5116. // In the middle of the previous element, new x shall be at the
  5117. // boundary start. Extending if further if the affected bondary
  5118. // placed on top of the current one.
  5119. xNew = affectedBoundary.index > boundary.index ?
  5120. affectedBoundary.x1New : boundary.x1;
  5121. } else if (affectedBoundary.x2New === undefined) {
  5122. // We have some space in between, new x in middle will be a fair
  5123. // choice.
  5124. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5125. } else {
  5126. // Affected boundary has x2new set, using it as new x.
  5127. xNew = affectedBoundary.x2New;
  5128. }
  5129. if (xNew > maxXNew) {
  5130. maxXNew = xNew;
  5131. }
  5132. }
  5133. // Set new x1 for current boundary.
  5134. boundary.x1New = maxXNew;
  5135. // Adjusts new x2 for the affected boundaries.
  5136. for (q = i; q <= j; q++) {
  5137. horizonPart = horizon[q];
  5138. affectedBoundary = horizonPart.boundary;
  5139. if (affectedBoundary.x2New === undefined) {
  5140. // Was not set yet, choosing new x if possible.
  5141. if (affectedBoundary.x2 > boundary.x1) {
  5142. // Current and affected boundaries intersect. If affected boundary
  5143. // is placed on top of the current, shrinking the affected.
  5144. if (affectedBoundary.index > boundary.index) {
  5145. affectedBoundary.x2New = affectedBoundary.x2;
  5146. }
  5147. } else {
  5148. affectedBoundary.x2New = maxXNew;
  5149. }
  5150. } else if (affectedBoundary.x2New > maxXNew) {
  5151. // Affected boundary is touching new x, pushing it back.
  5152. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5153. }
  5154. }
  5155. // Fixing the horizon.
  5156. var changedHorizon = [], lastBoundary = null;
  5157. for (q = i; q <= j; q++) {
  5158. horizonPart = horizon[q];
  5159. affectedBoundary = horizonPart.boundary;
  5160. // Checking which boundary will be visible.
  5161. var useBoundary = affectedBoundary.x2 > boundary.x2 ?
  5162. affectedBoundary : boundary;
  5163. if (lastBoundary === useBoundary) {
  5164. // Merging with previous.
  5165. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5166. } else {
  5167. changedHorizon.push({
  5168. start: horizonPart.start,
  5169. end: horizonPart.end,
  5170. boundary: useBoundary
  5171. });
  5172. lastBoundary = useBoundary;
  5173. }
  5174. }
  5175. if (horizon[i].start < boundary.y1) {
  5176. changedHorizon[0].start = boundary.y1;
  5177. changedHorizon.unshift({
  5178. start: horizon[i].start,
  5179. end: boundary.y1,
  5180. boundary: horizon[i].boundary
  5181. });
  5182. }
  5183. if (boundary.y2 < horizon[j].end) {
  5184. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5185. changedHorizon.push({
  5186. start: boundary.y2,
  5187. end: horizon[j].end,
  5188. boundary: horizon[j].boundary
  5189. });
  5190. }
  5191. // Set x2 new of boundary that is no longer visible (see overlapping case
  5192. // above).
  5193. // TODO more efficient, e.g. via reference counting.
  5194. for (q = i; q <= j; q++) {
  5195. horizonPart = horizon[q];
  5196. affectedBoundary = horizonPart.boundary;
  5197. if (affectedBoundary.x2New !== undefined) {
  5198. continue;
  5199. }
  5200. var used = false;
  5201. for (k = i - 1; !used && k >= 0 &&
  5202. horizon[k].start >= affectedBoundary.y1; k--) {
  5203. used = horizon[k].boundary === affectedBoundary;
  5204. }
  5205. for (k = j + 1; !used && k < horizon.length &&
  5206. horizon[k].end <= affectedBoundary.y2; k++) {
  5207. used = horizon[k].boundary === affectedBoundary;
  5208. }
  5209. for (k = 0; !used && k < changedHorizon.length; k++) {
  5210. used = changedHorizon[k].boundary === affectedBoundary;
  5211. }
  5212. if (!used) {
  5213. affectedBoundary.x2New = maxXNew;
  5214. }
  5215. }
  5216. Array.prototype.splice.apply(horizon,
  5217. [i, j - i + 1].concat(changedHorizon));
  5218. });
  5219. // Set new x2 for all unset boundaries.
  5220. horizon.forEach(function (horizonPart) {
  5221. var affectedBoundary = horizonPart.boundary;
  5222. if (affectedBoundary.x2New === undefined) {
  5223. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5224. }
  5225. });
  5226. }
  5227. /**
  5228. * Text layer rendering task.
  5229. *
  5230. * @param {TextContent} textContent
  5231. * @param {HTMLElement} container
  5232. * @param {PageViewport} viewport
  5233. * @param {Array} textDivs
  5234. * @param {boolean} enhanceTextSelection
  5235. * @private
  5236. */
  5237. function TextLayerRenderTask(textContent, container, viewport, textDivs,
  5238. enhanceTextSelection) {
  5239. this._textContent = textContent;
  5240. this._container = container;
  5241. this._viewport = viewport;
  5242. this._textDivs = textDivs || [];
  5243. this._textDivProperties = new WeakMap();
  5244. this._renderingDone = false;
  5245. this._canceled = false;
  5246. this._capability = createPromiseCapability();
  5247. this._renderTimer = null;
  5248. this._bounds = [];
  5249. this._enhanceTextSelection = !!enhanceTextSelection;
  5250. }
  5251. TextLayerRenderTask.prototype = {
  5252. get promise() {
  5253. return this._capability.promise;
  5254. },
  5255. cancel: function TextLayer_cancel() {
  5256. this._canceled = true;
  5257. if (this._renderTimer !== null) {
  5258. clearTimeout(this._renderTimer);
  5259. this._renderTimer = null;
  5260. }
  5261. this._capability.reject('canceled');
  5262. },
  5263. _render: function TextLayer_render(timeout) {
  5264. var textItems = this._textContent.items;
  5265. var textStyles = this._textContent.styles;
  5266. for (var i = 0, len = textItems.length; i < len; i++) {
  5267. appendText(this, textItems[i], textStyles);
  5268. }
  5269. if (!timeout) { // Render right away
  5270. render(this);
  5271. } else { // Schedule
  5272. var self = this;
  5273. this._renderTimer = setTimeout(function() {
  5274. render(self);
  5275. self._renderTimer = null;
  5276. }, timeout);
  5277. }
  5278. },
  5279. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5280. if (!this._enhanceTextSelection || !this._renderingDone) {
  5281. return;
  5282. }
  5283. if (this._bounds !== null) {
  5284. expand(this);
  5285. this._bounds = null;
  5286. }
  5287. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5288. var div = this._textDivs[i];
  5289. var divProperties = this._textDivProperties.get(div);
  5290. if (divProperties.isWhitespace) {
  5291. continue;
  5292. }
  5293. if (expandDivs) {
  5294. var transform = '', padding = '';
  5295. if (divProperties.scale !== 1) {
  5296. transform = 'scaleX(' + divProperties.scale + ')';
  5297. }
  5298. if (divProperties.angle !== 0) {
  5299. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5300. }
  5301. if (divProperties.paddingLeft !== 0) {
  5302. padding += ' padding-left: ' +
  5303. (divProperties.paddingLeft / divProperties.scale) + 'px;';
  5304. transform += ' translateX(' +
  5305. (-divProperties.paddingLeft / divProperties.scale) + 'px)';
  5306. }
  5307. if (divProperties.paddingTop !== 0) {
  5308. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5309. transform += ' translateY(' + (-divProperties.paddingTop) + 'px)';
  5310. }
  5311. if (divProperties.paddingRight !== 0) {
  5312. padding += ' padding-right: ' +
  5313. (divProperties.paddingRight / divProperties.scale) + 'px;';
  5314. }
  5315. if (divProperties.paddingBottom !== 0) {
  5316. padding += ' padding-bottom: ' +
  5317. divProperties.paddingBottom + 'px;';
  5318. }
  5319. if (padding !== '') {
  5320. div.setAttribute('style', divProperties.style + padding);
  5321. }
  5322. if (transform !== '') {
  5323. CustomStyle.setProp('transform', div, transform);
  5324. }
  5325. } else {
  5326. div.style.padding = 0;
  5327. CustomStyle.setProp('transform', div,
  5328. divProperties.originalTransform || '');
  5329. }
  5330. }
  5331. },
  5332. };
  5333. /**
  5334. * Starts rendering of the text layer.
  5335. *
  5336. * @param {TextLayerRenderParameters} renderParameters
  5337. * @returns {TextLayerRenderTask}
  5338. */
  5339. function renderTextLayer(renderParameters) {
  5340. var task = new TextLayerRenderTask(renderParameters.textContent,
  5341. renderParameters.container,
  5342. renderParameters.viewport,
  5343. renderParameters.textDivs,
  5344. renderParameters.enhanceTextSelection);
  5345. task._render(renderParameters.timeout);
  5346. return task;
  5347. }
  5348. return renderTextLayer;
  5349. })();
  5350. exports.renderTextLayer = renderTextLayer;
  5351. }));
  5352. (function (root, factory) {
  5353. {
  5354. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil,
  5355. root.pdfjsDisplayDOMUtils);
  5356. }
  5357. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5358. var shadow = sharedUtil.shadow;
  5359. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5360. var WebGLUtils = (function WebGLUtilsClosure() {
  5361. function loadShader(gl, code, shaderType) {
  5362. var shader = gl.createShader(shaderType);
  5363. gl.shaderSource(shader, code);
  5364. gl.compileShader(shader);
  5365. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5366. if (!compiled) {
  5367. var errorMsg = gl.getShaderInfoLog(shader);
  5368. throw new Error('Error during shader compilation: ' + errorMsg);
  5369. }
  5370. return shader;
  5371. }
  5372. function createVertexShader(gl, code) {
  5373. return loadShader(gl, code, gl.VERTEX_SHADER);
  5374. }
  5375. function createFragmentShader(gl, code) {
  5376. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5377. }
  5378. function createProgram(gl, shaders) {
  5379. var program = gl.createProgram();
  5380. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5381. gl.attachShader(program, shaders[i]);
  5382. }
  5383. gl.linkProgram(program);
  5384. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5385. if (!linked) {
  5386. var errorMsg = gl.getProgramInfoLog(program);
  5387. throw new Error('Error during program linking: ' + errorMsg);
  5388. }
  5389. return program;
  5390. }
  5391. function createTexture(gl, image, textureId) {
  5392. gl.activeTexture(textureId);
  5393. var texture = gl.createTexture();
  5394. gl.bindTexture(gl.TEXTURE_2D, texture);
  5395. // Set the parameters so we can render any size image.
  5396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5399. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5400. // Upload the image into the texture.
  5401. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5402. return texture;
  5403. }
  5404. var currentGL, currentCanvas;
  5405. function generateGL() {
  5406. if (currentGL) {
  5407. return;
  5408. }
  5409. currentCanvas = document.createElement('canvas');
  5410. currentGL = currentCanvas.getContext('webgl',
  5411. { premultipliedalpha: false });
  5412. }
  5413. var smaskVertexShaderCode = '\
  5414. attribute vec2 a_position; \
  5415. attribute vec2 a_texCoord; \
  5416. \
  5417. uniform vec2 u_resolution; \
  5418. \
  5419. varying vec2 v_texCoord; \
  5420. \
  5421. void main() { \
  5422. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5423. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5424. \
  5425. v_texCoord = a_texCoord; \
  5426. } ';
  5427. var smaskFragmentShaderCode = '\
  5428. precision mediump float; \
  5429. \
  5430. uniform vec4 u_backdrop; \
  5431. uniform int u_subtype; \
  5432. uniform sampler2D u_image; \
  5433. uniform sampler2D u_mask; \
  5434. \
  5435. varying vec2 v_texCoord; \
  5436. \
  5437. void main() { \
  5438. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5439. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5440. if (u_backdrop.a > 0.0) { \
  5441. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5442. u_backdrop.rgb * (1.0 - maskColor.a); \
  5443. } \
  5444. float lum; \
  5445. if (u_subtype == 0) { \
  5446. lum = maskColor.a; \
  5447. } else { \
  5448. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5449. maskColor.b * 0.11; \
  5450. } \
  5451. imageColor.a *= lum; \
  5452. imageColor.rgb *= imageColor.a; \
  5453. gl_FragColor = imageColor; \
  5454. } ';
  5455. var smaskCache = null;
  5456. function initSmaskGL() {
  5457. var canvas, gl;
  5458. generateGL();
  5459. canvas = currentCanvas;
  5460. currentCanvas = null;
  5461. gl = currentGL;
  5462. currentGL = null;
  5463. // setup a GLSL program
  5464. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5465. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5466. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5467. gl.useProgram(program);
  5468. var cache = {};
  5469. cache.gl = gl;
  5470. cache.canvas = canvas;
  5471. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5472. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5473. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5474. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5475. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5476. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5477. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5478. // provide texture coordinates for the rectangle.
  5479. var texCoordBuffer = gl.createBuffer();
  5480. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5481. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5482. 0.0, 0.0,
  5483. 1.0, 0.0,
  5484. 0.0, 1.0,
  5485. 0.0, 1.0,
  5486. 1.0, 0.0,
  5487. 1.0, 1.0]), gl.STATIC_DRAW);
  5488. gl.enableVertexAttribArray(texCoordLocation);
  5489. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5490. gl.uniform1i(texLayerLocation, 0);
  5491. gl.uniform1i(texMaskLocation, 1);
  5492. smaskCache = cache;
  5493. }
  5494. function composeSMask(layer, mask, properties) {
  5495. var width = layer.width, height = layer.height;
  5496. if (!smaskCache) {
  5497. initSmaskGL();
  5498. }
  5499. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5500. canvas.width = width;
  5501. canvas.height = height;
  5502. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5503. gl.uniform2f(cache.resolutionLocation, width, height);
  5504. if (properties.backdrop) {
  5505. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5506. properties.backdrop[1], properties.backdrop[2], 1);
  5507. } else {
  5508. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5509. }
  5510. gl.uniform1i(cache.subtypeLocation,
  5511. properties.subtype === 'Luminosity' ? 1 : 0);
  5512. // Create a textures
  5513. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5514. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5515. // Create a buffer and put a single clipspace rectangle in
  5516. // it (2 triangles)
  5517. var buffer = gl.createBuffer();
  5518. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5519. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5520. 0, 0,
  5521. width, 0,
  5522. 0, height,
  5523. 0, height,
  5524. width, 0,
  5525. width, height]), gl.STATIC_DRAW);
  5526. gl.enableVertexAttribArray(cache.positionLocation);
  5527. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5528. // draw
  5529. gl.clearColor(0, 0, 0, 0);
  5530. gl.enable(gl.BLEND);
  5531. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5532. gl.clear(gl.COLOR_BUFFER_BIT);
  5533. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5534. gl.flush();
  5535. gl.deleteTexture(texture);
  5536. gl.deleteTexture(maskTexture);
  5537. gl.deleteBuffer(buffer);
  5538. return canvas;
  5539. }
  5540. var figuresVertexShaderCode = '\
  5541. attribute vec2 a_position; \
  5542. attribute vec3 a_color; \
  5543. \
  5544. uniform vec2 u_resolution; \
  5545. uniform vec2 u_scale; \
  5546. uniform vec2 u_offset; \
  5547. \
  5548. varying vec4 v_color; \
  5549. \
  5550. void main() { \
  5551. vec2 position = (a_position + u_offset) * u_scale; \
  5552. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5553. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5554. \
  5555. v_color = vec4(a_color / 255.0, 1.0); \
  5556. } ';
  5557. var figuresFragmentShaderCode = '\
  5558. precision mediump float; \
  5559. \
  5560. varying vec4 v_color; \
  5561. \
  5562. void main() { \
  5563. gl_FragColor = v_color; \
  5564. } ';
  5565. var figuresCache = null;
  5566. function initFiguresGL() {
  5567. var canvas, gl;
  5568. generateGL();
  5569. canvas = currentCanvas;
  5570. currentCanvas = null;
  5571. gl = currentGL;
  5572. currentGL = null;
  5573. // setup a GLSL program
  5574. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5575. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5576. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5577. gl.useProgram(program);
  5578. var cache = {};
  5579. cache.gl = gl;
  5580. cache.canvas = canvas;
  5581. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5582. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5583. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5584. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5585. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5586. figuresCache = cache;
  5587. }
  5588. function drawFigures(width, height, backgroundColor, figures, context) {
  5589. if (!figuresCache) {
  5590. initFiguresGL();
  5591. }
  5592. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5593. canvas.width = width;
  5594. canvas.height = height;
  5595. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5596. gl.uniform2f(cache.resolutionLocation, width, height);
  5597. // count triangle points
  5598. var count = 0;
  5599. var i, ii, rows;
  5600. for (i = 0, ii = figures.length; i < ii; i++) {
  5601. switch (figures[i].type) {
  5602. case 'lattice':
  5603. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5604. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5605. break;
  5606. case 'triangles':
  5607. count += figures[i].coords.length;
  5608. break;
  5609. }
  5610. }
  5611. // transfer data
  5612. var coords = new Float32Array(count * 2);
  5613. var colors = new Uint8Array(count * 3);
  5614. var coordsMap = context.coords, colorsMap = context.colors;
  5615. var pIndex = 0, cIndex = 0;
  5616. for (i = 0, ii = figures.length; i < ii; i++) {
  5617. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5618. switch (figure.type) {
  5619. case 'lattice':
  5620. var cols = figure.verticesPerRow;
  5621. rows = (ps.length / cols) | 0;
  5622. for (var row = 1; row < rows; row++) {
  5623. var offset = row * cols + 1;
  5624. for (var col = 1; col < cols; col++, offset++) {
  5625. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5626. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5627. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5628. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5629. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5630. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5631. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5632. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5633. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5634. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5635. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5636. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5637. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5638. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5639. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5640. coords[pIndex + 6] = coords[pIndex + 2];
  5641. coords[pIndex + 7] = coords[pIndex + 3];
  5642. coords[pIndex + 8] = coords[pIndex + 4];
  5643. coords[pIndex + 9] = coords[pIndex + 5];
  5644. coords[pIndex + 10] = coordsMap[ps[offset]];
  5645. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5646. colors[cIndex + 9] = colors[cIndex + 3];
  5647. colors[cIndex + 10] = colors[cIndex + 4];
  5648. colors[cIndex + 11] = colors[cIndex + 5];
  5649. colors[cIndex + 12] = colors[cIndex + 6];
  5650. colors[cIndex + 13] = colors[cIndex + 7];
  5651. colors[cIndex + 14] = colors[cIndex + 8];
  5652. colors[cIndex + 15] = colorsMap[cs[offset]];
  5653. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5654. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5655. pIndex += 12;
  5656. cIndex += 18;
  5657. }
  5658. }
  5659. break;
  5660. case 'triangles':
  5661. for (var j = 0, jj = ps.length; j < jj; j++) {
  5662. coords[pIndex] = coordsMap[ps[j]];
  5663. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5664. colors[cIndex] = colorsMap[cs[j]];
  5665. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5666. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5667. pIndex += 2;
  5668. cIndex += 3;
  5669. }
  5670. break;
  5671. }
  5672. }
  5673. // draw
  5674. if (backgroundColor) {
  5675. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5676. backgroundColor[2] / 255, 1.0);
  5677. } else {
  5678. gl.clearColor(0, 0, 0, 0);
  5679. }
  5680. gl.clear(gl.COLOR_BUFFER_BIT);
  5681. var coordsBuffer = gl.createBuffer();
  5682. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5683. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5684. gl.enableVertexAttribArray(cache.positionLocation);
  5685. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5686. var colorsBuffer = gl.createBuffer();
  5687. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5688. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5689. gl.enableVertexAttribArray(cache.colorLocation);
  5690. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5691. 0, 0);
  5692. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5693. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5694. gl.drawArrays(gl.TRIANGLES, 0, count);
  5695. gl.flush();
  5696. gl.deleteBuffer(coordsBuffer);
  5697. gl.deleteBuffer(colorsBuffer);
  5698. return canvas;
  5699. }
  5700. function cleanup() {
  5701. if (smaskCache && smaskCache.canvas) {
  5702. smaskCache.canvas.width = 0;
  5703. smaskCache.canvas.height = 0;
  5704. }
  5705. if (figuresCache && figuresCache.canvas) {
  5706. figuresCache.canvas.width = 0;
  5707. figuresCache.canvas.height = 0;
  5708. }
  5709. smaskCache = null;
  5710. figuresCache = null;
  5711. }
  5712. return {
  5713. get isEnabled() {
  5714. if (getDefaultSetting('disableWebGL')) {
  5715. return false;
  5716. }
  5717. var enabled = false;
  5718. try {
  5719. generateGL();
  5720. enabled = !!currentGL;
  5721. } catch (e) { }
  5722. return shadow(this, 'isEnabled', enabled);
  5723. },
  5724. composeSMask: composeSMask,
  5725. drawFigures: drawFigures,
  5726. clear: cleanup
  5727. };
  5728. })();
  5729. exports.WebGLUtils = WebGLUtils;
  5730. }));
  5731. (function (root, factory) {
  5732. {
  5733. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5734. root.pdfjsDisplayWebGL);
  5735. }
  5736. }(this, function (exports, sharedUtil, displayWebGL) {
  5737. var Util = sharedUtil.Util;
  5738. var info = sharedUtil.info;
  5739. var isArray = sharedUtil.isArray;
  5740. var error = sharedUtil.error;
  5741. var WebGLUtils = displayWebGL.WebGLUtils;
  5742. var ShadingIRs = {};
  5743. ShadingIRs.RadialAxial = {
  5744. fromIR: function RadialAxial_fromIR(raw) {
  5745. var type = raw[1];
  5746. var colorStops = raw[2];
  5747. var p0 = raw[3];
  5748. var p1 = raw[4];
  5749. var r0 = raw[5];
  5750. var r1 = raw[6];
  5751. return {
  5752. type: 'Pattern',
  5753. getPattern: function RadialAxial_getPattern(ctx) {
  5754. var grad;
  5755. if (type === 'axial') {
  5756. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5757. } else if (type === 'radial') {
  5758. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5759. }
  5760. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5761. var c = colorStops[i];
  5762. grad.addColorStop(c[0], c[1]);
  5763. }
  5764. return grad;
  5765. }
  5766. };
  5767. }
  5768. };
  5769. var createMeshCanvas = (function createMeshCanvasClosure() {
  5770. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5771. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5772. var coords = context.coords, colors = context.colors;
  5773. var bytes = data.data, rowSize = data.width * 4;
  5774. var tmp;
  5775. if (coords[p1 + 1] > coords[p2 + 1]) {
  5776. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5777. }
  5778. if (coords[p2 + 1] > coords[p3 + 1]) {
  5779. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5780. }
  5781. if (coords[p1 + 1] > coords[p2 + 1]) {
  5782. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5783. }
  5784. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5785. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5786. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5787. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5788. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5789. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5790. if (y1 >= y3) {
  5791. return;
  5792. }
  5793. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5794. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5795. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5796. var minY = Math.round(y1), maxY = Math.round(y3);
  5797. var xa, car, cag, cab;
  5798. var xb, cbr, cbg, cbb;
  5799. var k;
  5800. for (var y = minY; y <= maxY; y++) {
  5801. if (y < y2) {
  5802. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5803. xa = x1 - (x1 - x2) * k;
  5804. car = c1r - (c1r - c2r) * k;
  5805. cag = c1g - (c1g - c2g) * k;
  5806. cab = c1b - (c1b - c2b) * k;
  5807. } else {
  5808. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5809. xa = x2 - (x2 - x3) * k;
  5810. car = c2r - (c2r - c3r) * k;
  5811. cag = c2g - (c2g - c3g) * k;
  5812. cab = c2b - (c2b - c3b) * k;
  5813. }
  5814. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5815. xb = x1 - (x1 - x3) * k;
  5816. cbr = c1r - (c1r - c3r) * k;
  5817. cbg = c1g - (c1g - c3g) * k;
  5818. cbb = c1b - (c1b - c3b) * k;
  5819. var x1_ = Math.round(Math.min(xa, xb));
  5820. var x2_ = Math.round(Math.max(xa, xb));
  5821. var j = rowSize * y + x1_ * 4;
  5822. for (var x = x1_; x <= x2_; x++) {
  5823. k = (xa - x) / (xa - xb);
  5824. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5825. bytes[j++] = (car - (car - cbr) * k) | 0;
  5826. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5827. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5828. bytes[j++] = 255;
  5829. }
  5830. }
  5831. }
  5832. function drawFigure(data, figure, context) {
  5833. var ps = figure.coords;
  5834. var cs = figure.colors;
  5835. var i, ii;
  5836. switch (figure.type) {
  5837. case 'lattice':
  5838. var verticesPerRow = figure.verticesPerRow;
  5839. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5840. var cols = verticesPerRow - 1;
  5841. for (i = 0; i < rows; i++) {
  5842. var q = i * verticesPerRow;
  5843. for (var j = 0; j < cols; j++, q++) {
  5844. drawTriangle(data, context,
  5845. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5846. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5847. drawTriangle(data, context,
  5848. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5849. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5850. }
  5851. }
  5852. break;
  5853. case 'triangles':
  5854. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5855. drawTriangle(data, context,
  5856. ps[i], ps[i + 1], ps[i + 2],
  5857. cs[i], cs[i + 1], cs[i + 2]);
  5858. }
  5859. break;
  5860. default:
  5861. error('illigal figure');
  5862. break;
  5863. }
  5864. }
  5865. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5866. backgroundColor, cachedCanvases) {
  5867. // we will increase scale on some weird factor to let antialiasing take
  5868. // care of "rough" edges
  5869. var EXPECTED_SCALE = 1.1;
  5870. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5871. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5872. // We need to keep transparent border around our pattern for fill():
  5873. // createPattern with 'no-repeat' will bleed edges across entire area.
  5874. var BORDER_SIZE = 2;
  5875. var offsetX = Math.floor(bounds[0]);
  5876. var offsetY = Math.floor(bounds[1]);
  5877. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5878. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5879. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5880. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5881. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5882. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5883. var scaleX = boundsWidth / width;
  5884. var scaleY = boundsHeight / height;
  5885. var context = {
  5886. coords: coords,
  5887. colors: colors,
  5888. offsetX: -offsetX,
  5889. offsetY: -offsetY,
  5890. scaleX: 1 / scaleX,
  5891. scaleY: 1 / scaleY
  5892. };
  5893. var paddedWidth = width + BORDER_SIZE * 2;
  5894. var paddedHeight = height + BORDER_SIZE * 2;
  5895. var canvas, tmpCanvas, i, ii;
  5896. if (WebGLUtils.isEnabled) {
  5897. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5898. figures, context);
  5899. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5900. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5901. false);
  5902. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5903. canvas = tmpCanvas.canvas;
  5904. } else {
  5905. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5906. false);
  5907. var tmpCtx = tmpCanvas.context;
  5908. var data = tmpCtx.createImageData(width, height);
  5909. if (backgroundColor) {
  5910. var bytes = data.data;
  5911. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5912. bytes[i] = backgroundColor[0];
  5913. bytes[i + 1] = backgroundColor[1];
  5914. bytes[i + 2] = backgroundColor[2];
  5915. bytes[i + 3] = 255;
  5916. }
  5917. }
  5918. for (i = 0; i < figures.length; i++) {
  5919. drawFigure(data, figures[i], context);
  5920. }
  5921. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5922. canvas = tmpCanvas.canvas;
  5923. }
  5924. return {canvas: canvas,
  5925. offsetX: offsetX - BORDER_SIZE * scaleX,
  5926. offsetY: offsetY - BORDER_SIZE * scaleY,
  5927. scaleX: scaleX, scaleY: scaleY};
  5928. }
  5929. return createMeshCanvas;
  5930. })();
  5931. ShadingIRs.Mesh = {
  5932. fromIR: function Mesh_fromIR(raw) {
  5933. //var type = raw[1];
  5934. var coords = raw[2];
  5935. var colors = raw[3];
  5936. var figures = raw[4];
  5937. var bounds = raw[5];
  5938. var matrix = raw[6];
  5939. //var bbox = raw[7];
  5940. var background = raw[8];
  5941. return {
  5942. type: 'Pattern',
  5943. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5944. var scale;
  5945. if (shadingFill) {
  5946. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5947. } else {
  5948. // Obtain scale from matrix and current transformation matrix.
  5949. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5950. if (matrix) {
  5951. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5952. scale = [scale[0] * matrixScale[0],
  5953. scale[1] * matrixScale[1]];
  5954. }
  5955. }
  5956. // Rasterizing on the main thread since sending/queue large canvases
  5957. // might cause OOM.
  5958. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5959. colors, figures, shadingFill ? null : background,
  5960. owner.cachedCanvases);
  5961. if (!shadingFill) {
  5962. ctx.setTransform.apply(ctx, owner.baseTransform);
  5963. if (matrix) {
  5964. ctx.transform.apply(ctx, matrix);
  5965. }
  5966. }
  5967. ctx.translate(temporaryPatternCanvas.offsetX,
  5968. temporaryPatternCanvas.offsetY);
  5969. ctx.scale(temporaryPatternCanvas.scaleX,
  5970. temporaryPatternCanvas.scaleY);
  5971. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5972. }
  5973. };
  5974. }
  5975. };
  5976. ShadingIRs.Dummy = {
  5977. fromIR: function Dummy_fromIR() {
  5978. return {
  5979. type: 'Pattern',
  5980. getPattern: function Dummy_fromIR_getPattern() {
  5981. return 'hotpink';
  5982. }
  5983. };
  5984. }
  5985. };
  5986. function getShadingPatternFromIR(raw) {
  5987. var shadingIR = ShadingIRs[raw[0]];
  5988. if (!shadingIR) {
  5989. error('Unknown IR type: ' + raw[0]);
  5990. }
  5991. return shadingIR.fromIR(raw);
  5992. }
  5993. var TilingPattern = (function TilingPatternClosure() {
  5994. var PaintType = {
  5995. COLORED: 1,
  5996. UNCOLORED: 2
  5997. };
  5998. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5999. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6000. this.operatorList = IR[2];
  6001. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  6002. this.bbox = IR[4];
  6003. this.xstep = IR[5];
  6004. this.ystep = IR[6];
  6005. this.paintType = IR[7];
  6006. this.tilingType = IR[8];
  6007. this.color = color;
  6008. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6009. this.baseTransform = baseTransform;
  6010. this.type = 'Pattern';
  6011. this.ctx = ctx;
  6012. }
  6013. TilingPattern.prototype = {
  6014. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6015. var operatorList = this.operatorList;
  6016. var bbox = this.bbox;
  6017. var xstep = this.xstep;
  6018. var ystep = this.ystep;
  6019. var paintType = this.paintType;
  6020. var tilingType = this.tilingType;
  6021. var color = this.color;
  6022. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6023. info('TilingType: ' + tilingType);
  6024. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6025. var topLeft = [x0, y0];
  6026. // we want the canvas to be as large as the step size
  6027. var botRight = [x0 + xstep, y0 + ystep];
  6028. var width = botRight[0] - topLeft[0];
  6029. var height = botRight[1] - topLeft[1];
  6030. // Obtain scale from matrix and current transformation matrix.
  6031. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6032. var curMatrixScale = Util.singularValueDecompose2dScale(
  6033. this.baseTransform);
  6034. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  6035. matrixScale[1] * curMatrixScale[1]];
  6036. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6037. // Use width and height values that are as close as possible to the end
  6038. // result when the pattern is used. Too low value makes the pattern look
  6039. // blurry. Too large value makes it look too crispy.
  6040. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  6041. MAX_PATTERN_SIZE);
  6042. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  6043. MAX_PATTERN_SIZE);
  6044. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  6045. width, height, true);
  6046. var tmpCtx = tmpCanvas.context;
  6047. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6048. graphics.groupLevel = owner.groupLevel;
  6049. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6050. this.setScale(width, height, xstep, ystep);
  6051. this.transformToScale(graphics);
  6052. // transform coordinates to pattern space
  6053. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  6054. graphics.transform.apply(graphics, tmpTranslate);
  6055. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6056. graphics.executeOperatorList(operatorList);
  6057. return tmpCanvas.canvas;
  6058. },
  6059. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6060. this.scale = [width / xstep, height / ystep];
  6061. },
  6062. transformToScale: function TilingPattern_transformToScale(graphics) {
  6063. var scale = this.scale;
  6064. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  6065. graphics.transform.apply(graphics, tmpScale);
  6066. },
  6067. scaleToContext: function TilingPattern_scaleToContext() {
  6068. var scale = this.scale;
  6069. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6070. },
  6071. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6072. if (bbox && isArray(bbox) && bbox.length === 4) {
  6073. var bboxWidth = x1 - x0;
  6074. var bboxHeight = y1 - y0;
  6075. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6076. graphics.clip();
  6077. graphics.endPath();
  6078. }
  6079. },
  6080. setFillAndStrokeStyleToContext:
  6081. function setFillAndStrokeStyleToContext(context, paintType, color) {
  6082. switch (paintType) {
  6083. case PaintType.COLORED:
  6084. var ctx = this.ctx;
  6085. context.fillStyle = ctx.fillStyle;
  6086. context.strokeStyle = ctx.strokeStyle;
  6087. break;
  6088. case PaintType.UNCOLORED:
  6089. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6090. context.fillStyle = cssColor;
  6091. context.strokeStyle = cssColor;
  6092. break;
  6093. default:
  6094. error('Unsupported paint type: ' + paintType);
  6095. }
  6096. },
  6097. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6098. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6099. ctx = this.ctx;
  6100. ctx.setTransform.apply(ctx, this.baseTransform);
  6101. ctx.transform.apply(ctx, this.matrix);
  6102. this.scaleToContext();
  6103. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6104. }
  6105. };
  6106. return TilingPattern;
  6107. })();
  6108. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6109. exports.TilingPattern = TilingPattern;
  6110. }));
  6111. (function (root, factory) {
  6112. {
  6113. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  6114. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
  6115. root.pdfjsDisplayWebGL);
  6116. }
  6117. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
  6118. displayWebGL) {
  6119. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6120. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6121. var ImageKind = sharedUtil.ImageKind;
  6122. var OPS = sharedUtil.OPS;
  6123. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6124. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6125. var Util = sharedUtil.Util;
  6126. var assert = sharedUtil.assert;
  6127. var info = sharedUtil.info;
  6128. var isNum = sharedUtil.isNum;
  6129. var isArray = sharedUtil.isArray;
  6130. var isLittleEndian = sharedUtil.isLittleEndian;
  6131. var error = sharedUtil.error;
  6132. var shadow = sharedUtil.shadow;
  6133. var warn = sharedUtil.warn;
  6134. var TilingPattern = displayPatternHelper.TilingPattern;
  6135. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6136. var WebGLUtils = displayWebGL.WebGLUtils;
  6137. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6138. // <canvas> contexts store most of the state we need natively.
  6139. // However, PDF needs a bit more state, which we store here.
  6140. // Minimal font size that would be used during canvas fillText operations.
  6141. var MIN_FONT_SIZE = 16;
  6142. // Maximum font size that would be used during canvas fillText operations.
  6143. var MAX_FONT_SIZE = 100;
  6144. var MAX_GROUP_SIZE = 4096;
  6145. // Heuristic value used when enforcing minimum line widths.
  6146. var MIN_WIDTH_FACTOR = 0.65;
  6147. var COMPILE_TYPE3_GLYPHS = true;
  6148. var MAX_SIZE_TO_COMPILE = 1000;
  6149. var FULL_CHUNK_HEIGHT = 16;
  6150. var HasCanvasTypedArraysCached = {
  6151. get value() {
  6152. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6153. }
  6154. };
  6155. var IsLittleEndianCached = {
  6156. get value() {
  6157. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6158. }
  6159. };
  6160. function createScratchCanvas(width, height) {
  6161. var canvas = document.createElement('canvas');
  6162. canvas.width = width;
  6163. canvas.height = height;
  6164. return canvas;
  6165. }
  6166. function addContextCurrentTransform(ctx) {
  6167. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6168. if (!ctx.mozCurrentTransform) {
  6169. ctx._originalSave = ctx.save;
  6170. ctx._originalRestore = ctx.restore;
  6171. ctx._originalRotate = ctx.rotate;
  6172. ctx._originalScale = ctx.scale;
  6173. ctx._originalTranslate = ctx.translate;
  6174. ctx._originalTransform = ctx.transform;
  6175. ctx._originalSetTransform = ctx.setTransform;
  6176. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  6177. ctx._transformStack = [];
  6178. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6179. get: function getCurrentTransform() {
  6180. return this._transformMatrix;
  6181. }
  6182. });
  6183. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6184. get: function getCurrentTransformInverse() {
  6185. // Calculation done using WolframAlpha:
  6186. // http://www.wolframalpha.com/input/?
  6187. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6188. var m = this._transformMatrix;
  6189. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6190. var ad_bc = a * d - b * c;
  6191. var bc_ad = b * c - a * d;
  6192. return [
  6193. d / ad_bc,
  6194. b / bc_ad,
  6195. c / bc_ad,
  6196. a / ad_bc,
  6197. (d * e - c * f) / bc_ad,
  6198. (b * e - a * f) / ad_bc
  6199. ];
  6200. }
  6201. });
  6202. ctx.save = function ctxSave() {
  6203. var old = this._transformMatrix;
  6204. this._transformStack.push(old);
  6205. this._transformMatrix = old.slice(0, 6);
  6206. this._originalSave();
  6207. };
  6208. ctx.restore = function ctxRestore() {
  6209. var prev = this._transformStack.pop();
  6210. if (prev) {
  6211. this._transformMatrix = prev;
  6212. this._originalRestore();
  6213. }
  6214. };
  6215. ctx.translate = function ctxTranslate(x, y) {
  6216. var m = this._transformMatrix;
  6217. m[4] = m[0] * x + m[2] * y + m[4];
  6218. m[5] = m[1] * x + m[3] * y + m[5];
  6219. this._originalTranslate(x, y);
  6220. };
  6221. ctx.scale = function ctxScale(x, y) {
  6222. var m = this._transformMatrix;
  6223. m[0] = m[0] * x;
  6224. m[1] = m[1] * x;
  6225. m[2] = m[2] * y;
  6226. m[3] = m[3] * y;
  6227. this._originalScale(x, y);
  6228. };
  6229. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6230. var m = this._transformMatrix;
  6231. this._transformMatrix = [
  6232. m[0] * a + m[2] * b,
  6233. m[1] * a + m[3] * b,
  6234. m[0] * c + m[2] * d,
  6235. m[1] * c + m[3] * d,
  6236. m[0] * e + m[2] * f + m[4],
  6237. m[1] * e + m[3] * f + m[5]
  6238. ];
  6239. ctx._originalTransform(a, b, c, d, e, f);
  6240. };
  6241. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6242. this._transformMatrix = [a, b, c, d, e, f];
  6243. ctx._originalSetTransform(a, b, c, d, e, f);
  6244. };
  6245. ctx.rotate = function ctxRotate(angle) {
  6246. var cosValue = Math.cos(angle);
  6247. var sinValue = Math.sin(angle);
  6248. var m = this._transformMatrix;
  6249. this._transformMatrix = [
  6250. m[0] * cosValue + m[2] * sinValue,
  6251. m[1] * cosValue + m[3] * sinValue,
  6252. m[0] * (-sinValue) + m[2] * cosValue,
  6253. m[1] * (-sinValue) + m[3] * cosValue,
  6254. m[4],
  6255. m[5]
  6256. ];
  6257. this._originalRotate(angle);
  6258. };
  6259. }
  6260. }
  6261. var CachedCanvases = (function CachedCanvasesClosure() {
  6262. function CachedCanvases() {
  6263. this.cache = Object.create(null);
  6264. }
  6265. CachedCanvases.prototype = {
  6266. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  6267. trackTransform) {
  6268. var canvasEntry;
  6269. if (this.cache[id] !== undefined) {
  6270. canvasEntry = this.cache[id];
  6271. canvasEntry.canvas.width = width;
  6272. canvasEntry.canvas.height = height;
  6273. // reset canvas transform for emulated mozCurrentTransform, if needed
  6274. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6275. } else {
  6276. var canvas = createScratchCanvas(width, height);
  6277. var ctx = canvas.getContext('2d');
  6278. if (trackTransform) {
  6279. addContextCurrentTransform(ctx);
  6280. }
  6281. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  6282. }
  6283. return canvasEntry;
  6284. },
  6285. clear: function () {
  6286. for (var id in this.cache) {
  6287. var canvasEntry = this.cache[id];
  6288. // Zeroing the width and height causes Firefox to release graphics
  6289. // resources immediately, which can greatly reduce memory consumption.
  6290. canvasEntry.canvas.width = 0;
  6291. canvasEntry.canvas.height = 0;
  6292. delete this.cache[id];
  6293. }
  6294. }
  6295. };
  6296. return CachedCanvases;
  6297. })();
  6298. function compileType3Glyph(imgData) {
  6299. var POINT_TO_PROCESS_LIMIT = 1000;
  6300. var width = imgData.width, height = imgData.height;
  6301. var i, j, j0, width1 = width + 1;
  6302. var points = new Uint8Array(width1 * (height + 1));
  6303. var POINT_TYPES =
  6304. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6305. // decodes bit-packed mask data
  6306. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  6307. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6308. for (i = 0, ii = data0.length; i < ii; i++) {
  6309. var mask = 128, elem = data0[i];
  6310. while (mask > 0) {
  6311. data[pos++] = (elem & mask) ? 0 : 255;
  6312. mask >>= 1;
  6313. }
  6314. }
  6315. // finding iteresting points: every point is located between mask pixels,
  6316. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6317. // will have flags assigned based on neighboring mask pixels:
  6318. // 4 | 8
  6319. // --P--
  6320. // 2 | 1
  6321. // We are interested only in points with the flags:
  6322. // - outside corners: 1, 2, 4, 8;
  6323. // - inside corners: 7, 11, 13, 14;
  6324. // - and, intersections: 5, 10.
  6325. var count = 0;
  6326. pos = 0;
  6327. if (data[pos] !== 0) {
  6328. points[0] = 1;
  6329. ++count;
  6330. }
  6331. for (j = 1; j < width; j++) {
  6332. if (data[pos] !== data[pos + 1]) {
  6333. points[j] = data[pos] ? 2 : 1;
  6334. ++count;
  6335. }
  6336. pos++;
  6337. }
  6338. if (data[pos] !== 0) {
  6339. points[j] = 2;
  6340. ++count;
  6341. }
  6342. for (i = 1; i < height; i++) {
  6343. pos = i * lineSize;
  6344. j0 = i * width1;
  6345. if (data[pos - lineSize] !== data[pos]) {
  6346. points[j0] = data[pos] ? 1 : 8;
  6347. ++count;
  6348. }
  6349. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6350. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6351. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6352. for (j = 1; j < width; j++) {
  6353. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  6354. (data[pos - lineSize + 1] ? 8 : 0);
  6355. if (POINT_TYPES[sum]) {
  6356. points[j0 + j] = POINT_TYPES[sum];
  6357. ++count;
  6358. }
  6359. pos++;
  6360. }
  6361. if (data[pos - lineSize] !== data[pos]) {
  6362. points[j0 + j] = data[pos] ? 2 : 4;
  6363. ++count;
  6364. }
  6365. if (count > POINT_TO_PROCESS_LIMIT) {
  6366. return null;
  6367. }
  6368. }
  6369. pos = lineSize * (height - 1);
  6370. j0 = i * width1;
  6371. if (data[pos] !== 0) {
  6372. points[j0] = 8;
  6373. ++count;
  6374. }
  6375. for (j = 1; j < width; j++) {
  6376. if (data[pos] !== data[pos + 1]) {
  6377. points[j0 + j] = data[pos] ? 4 : 8;
  6378. ++count;
  6379. }
  6380. pos++;
  6381. }
  6382. if (data[pos] !== 0) {
  6383. points[j0 + j] = 4;
  6384. ++count;
  6385. }
  6386. if (count > POINT_TO_PROCESS_LIMIT) {
  6387. return null;
  6388. }
  6389. // building outlines
  6390. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6391. var outlines = [];
  6392. for (i = 0; count && i <= height; i++) {
  6393. var p = i * width1;
  6394. var end = p + width;
  6395. while (p < end && !points[p]) {
  6396. p++;
  6397. }
  6398. if (p === end) {
  6399. continue;
  6400. }
  6401. var coords = [p % width1, i];
  6402. var type = points[p], p0 = p, pp;
  6403. do {
  6404. var step = steps[type];
  6405. do {
  6406. p += step;
  6407. } while (!points[p]);
  6408. pp = points[p];
  6409. if (pp !== 5 && pp !== 10) {
  6410. // set new direction
  6411. type = pp;
  6412. // delete mark
  6413. points[p] = 0;
  6414. } else { // type is 5 or 10, ie, a crossing
  6415. // set new direction
  6416. type = pp & ((0x33 * type) >> 4);
  6417. // set new type for "future hit"
  6418. points[p] &= (type >> 2 | type << 2);
  6419. }
  6420. coords.push(p % width1);
  6421. coords.push((p / width1) | 0);
  6422. --count;
  6423. } while (p0 !== p);
  6424. outlines.push(coords);
  6425. --i;
  6426. }
  6427. var drawOutline = function(c) {
  6428. c.save();
  6429. // the path shall be painted in [0..1]x[0..1] space
  6430. c.scale(1 / width, -1 / height);
  6431. c.translate(0, -height);
  6432. c.beginPath();
  6433. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6434. var o = outlines[i];
  6435. c.moveTo(o[0], o[1]);
  6436. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6437. c.lineTo(o[j], o[j+1]);
  6438. }
  6439. }
  6440. c.fill();
  6441. c.beginPath();
  6442. c.restore();
  6443. };
  6444. return drawOutline;
  6445. }
  6446. var CanvasExtraState = (function CanvasExtraStateClosure() {
  6447. function CanvasExtraState(old) {
  6448. // Are soft masks and alpha values shapes or opacities?
  6449. this.alphaIsShape = false;
  6450. this.fontSize = 0;
  6451. this.fontSizeScale = 1;
  6452. this.textMatrix = IDENTITY_MATRIX;
  6453. this.textMatrixScale = 1;
  6454. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6455. this.leading = 0;
  6456. // Current point (in user coordinates)
  6457. this.x = 0;
  6458. this.y = 0;
  6459. // Start of text line (in text coordinates)
  6460. this.lineX = 0;
  6461. this.lineY = 0;
  6462. // Character and word spacing
  6463. this.charSpacing = 0;
  6464. this.wordSpacing = 0;
  6465. this.textHScale = 1;
  6466. this.textRenderingMode = TextRenderingMode.FILL;
  6467. this.textRise = 0;
  6468. // Default fore and background colors
  6469. this.fillColor = '#000000';
  6470. this.strokeColor = '#000000';
  6471. this.patternFill = false;
  6472. // Note: fill alpha applies to all non-stroking operations
  6473. this.fillAlpha = 1;
  6474. this.strokeAlpha = 1;
  6475. this.lineWidth = 1;
  6476. this.activeSMask = null;
  6477. this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
  6478. this.old = old;
  6479. }
  6480. CanvasExtraState.prototype = {
  6481. clone: function CanvasExtraState_clone() {
  6482. return Object.create(this);
  6483. },
  6484. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6485. this.x = x;
  6486. this.y = y;
  6487. }
  6488. };
  6489. return CanvasExtraState;
  6490. })();
  6491. var CanvasGraphics = (function CanvasGraphicsClosure() {
  6492. // Defines the time the executeOperatorList is going to be executing
  6493. // before it stops and shedules a continue of execution.
  6494. var EXECUTION_TIME = 15;
  6495. // Defines the number of steps before checking the execution time
  6496. var EXECUTION_STEPS = 10;
  6497. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6498. this.ctx = canvasCtx;
  6499. this.current = new CanvasExtraState();
  6500. this.stateStack = [];
  6501. this.pendingClip = null;
  6502. this.pendingEOFill = false;
  6503. this.res = null;
  6504. this.xobjs = null;
  6505. this.commonObjs = commonObjs;
  6506. this.objs = objs;
  6507. this.imageLayer = imageLayer;
  6508. this.groupStack = [];
  6509. this.processingType3 = null;
  6510. // Patterns are painted relative to the initial page/form transform, see pdf
  6511. // spec 8.7.2 NOTE 1.
  6512. this.baseTransform = null;
  6513. this.baseTransformStack = [];
  6514. this.groupLevel = 0;
  6515. this.smaskStack = [];
  6516. this.smaskCounter = 0;
  6517. this.tempSMask = null;
  6518. this.cachedCanvases = new CachedCanvases();
  6519. if (canvasCtx) {
  6520. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6521. // the transformation must already be set in canvasCtx._transformMatrix.
  6522. addContextCurrentTransform(canvasCtx);
  6523. }
  6524. this.cachedGetSinglePixelWidth = null;
  6525. }
  6526. function putBinaryImageData(ctx, imgData) {
  6527. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6528. ctx.putImageData(imgData, 0, 0);
  6529. return;
  6530. }
  6531. // Put the image data to the canvas in chunks, rather than putting the
  6532. // whole image at once. This saves JS memory, because the ImageData object
  6533. // is smaller. It also possibly saves C++ memory within the implementation
  6534. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6535. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6536. // because too many putImageData() calls will slow things down.
  6537. //
  6538. // Note: as written, if the last chunk is partial, the putImageData() call
  6539. // will (conceptually) put pixels past the bounds of the canvas. But
  6540. // that's ok; any such pixels are ignored.
  6541. var height = imgData.height, width = imgData.width;
  6542. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6543. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6544. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6545. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6546. var srcPos = 0, destPos;
  6547. var src = imgData.data;
  6548. var dest = chunkImgData.data;
  6549. var i, j, thisChunkHeight, elemsInThisChunk;
  6550. // There are multiple forms in which the pixel data can be passed, and
  6551. // imgData.kind tells us which one this is.
  6552. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6553. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6554. var srcLength = src.byteLength;
  6555. var dest32 = HasCanvasTypedArraysCached.value ?
  6556. new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6557. var dest32DataLength = dest32.length;
  6558. var fullSrcDiff = (width + 7) >> 3;
  6559. var white = 0xFFFFFFFF;
  6560. var black = (IsLittleEndianCached.value ||
  6561. !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
  6562. for (i = 0; i < totalChunks; i++) {
  6563. thisChunkHeight =
  6564. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6565. destPos = 0;
  6566. for (j = 0; j < thisChunkHeight; j++) {
  6567. var srcDiff = srcLength - srcPos;
  6568. var k = 0;
  6569. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  6570. var kEndUnrolled = kEnd & ~7;
  6571. var mask = 0;
  6572. var srcByte = 0;
  6573. for (; k < kEndUnrolled; k += 8) {
  6574. srcByte = src[srcPos++];
  6575. dest32[destPos++] = (srcByte & 128) ? white : black;
  6576. dest32[destPos++] = (srcByte & 64) ? white : black;
  6577. dest32[destPos++] = (srcByte & 32) ? white : black;
  6578. dest32[destPos++] = (srcByte & 16) ? white : black;
  6579. dest32[destPos++] = (srcByte & 8) ? white : black;
  6580. dest32[destPos++] = (srcByte & 4) ? white : black;
  6581. dest32[destPos++] = (srcByte & 2) ? white : black;
  6582. dest32[destPos++] = (srcByte & 1) ? white : black;
  6583. }
  6584. for (; k < kEnd; k++) {
  6585. if (mask === 0) {
  6586. srcByte = src[srcPos++];
  6587. mask = 128;
  6588. }
  6589. dest32[destPos++] = (srcByte & mask) ? white : black;
  6590. mask >>= 1;
  6591. }
  6592. }
  6593. // We ran out of input. Make all remaining pixels transparent.
  6594. while (destPos < dest32DataLength) {
  6595. dest32[destPos++] = 0;
  6596. }
  6597. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6598. }
  6599. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6600. // RGBA, 32-bits per pixel.
  6601. j = 0;
  6602. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6603. for (i = 0; i < fullChunks; i++) {
  6604. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6605. srcPos += elemsInThisChunk;
  6606. ctx.putImageData(chunkImgData, 0, j);
  6607. j += FULL_CHUNK_HEIGHT;
  6608. }
  6609. if (i < totalChunks) {
  6610. elemsInThisChunk = width * partialChunkHeight * 4;
  6611. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6612. ctx.putImageData(chunkImgData, 0, j);
  6613. }
  6614. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6615. // RGB, 24-bits per pixel.
  6616. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6617. elemsInThisChunk = width * thisChunkHeight;
  6618. for (i = 0; i < totalChunks; i++) {
  6619. if (i >= fullChunks) {
  6620. thisChunkHeight = partialChunkHeight;
  6621. elemsInThisChunk = width * thisChunkHeight;
  6622. }
  6623. destPos = 0;
  6624. for (j = elemsInThisChunk; j--;) {
  6625. dest[destPos++] = src[srcPos++];
  6626. dest[destPos++] = src[srcPos++];
  6627. dest[destPos++] = src[srcPos++];
  6628. dest[destPos++] = 255;
  6629. }
  6630. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6631. }
  6632. } else {
  6633. error('bad image kind: ' + imgData.kind);
  6634. }
  6635. }
  6636. function putBinaryImageMask(ctx, imgData) {
  6637. var height = imgData.height, width = imgData.width;
  6638. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6639. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6640. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6641. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6642. var srcPos = 0;
  6643. var src = imgData.data;
  6644. var dest = chunkImgData.data;
  6645. for (var i = 0; i < totalChunks; i++) {
  6646. var thisChunkHeight =
  6647. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6648. // Expand the mask so it can be used by the canvas. Any required
  6649. // inversion has already been handled.
  6650. var destPos = 3; // alpha component offset
  6651. for (var j = 0; j < thisChunkHeight; j++) {
  6652. var mask = 0;
  6653. for (var k = 0; k < width; k++) {
  6654. if (!mask) {
  6655. var elem = src[srcPos++];
  6656. mask = 128;
  6657. }
  6658. dest[destPos] = (elem & mask) ? 0 : 255;
  6659. destPos += 4;
  6660. mask >>= 1;
  6661. }
  6662. }
  6663. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6664. }
  6665. }
  6666. function copyCtxState(sourceCtx, destCtx) {
  6667. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6668. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6669. 'globalCompositeOperation', 'font'];
  6670. for (var i = 0, ii = properties.length; i < ii; i++) {
  6671. var property = properties[i];
  6672. if (sourceCtx[property] !== undefined) {
  6673. destCtx[property] = sourceCtx[property];
  6674. }
  6675. }
  6676. if (sourceCtx.setLineDash !== undefined) {
  6677. destCtx.setLineDash(sourceCtx.getLineDash());
  6678. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6679. }
  6680. }
  6681. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6682. var length = bytes.length;
  6683. for (var i = 3; i < length; i += 4) {
  6684. var alpha = bytes[i];
  6685. if (alpha === 0) {
  6686. bytes[i - 3] = r0;
  6687. bytes[i - 2] = g0;
  6688. bytes[i - 1] = b0;
  6689. } else if (alpha < 255) {
  6690. var alpha_ = 255 - alpha;
  6691. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6692. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6693. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6694. }
  6695. }
  6696. }
  6697. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6698. var length = maskData.length;
  6699. var scale = 1 / 255;
  6700. for (var i = 3; i < length; i += 4) {
  6701. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6702. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6703. }
  6704. }
  6705. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6706. var length = maskData.length;
  6707. for (var i = 3; i < length; i += 4) {
  6708. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6709. (maskData[i - 2] * 152) + // * 0.59 ....
  6710. (maskData[i - 1] * 28); // * 0.11 ....
  6711. layerData[i] = transferMap ?
  6712. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6713. (layerData[i] * y) >> 16;
  6714. }
  6715. }
  6716. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6717. subtype, backdrop, transferMap) {
  6718. var hasBackdrop = !!backdrop;
  6719. var r0 = hasBackdrop ? backdrop[0] : 0;
  6720. var g0 = hasBackdrop ? backdrop[1] : 0;
  6721. var b0 = hasBackdrop ? backdrop[2] : 0;
  6722. var composeFn;
  6723. if (subtype === 'Luminosity') {
  6724. composeFn = composeSMaskLuminosity;
  6725. } else {
  6726. composeFn = composeSMaskAlpha;
  6727. }
  6728. // processing image in chunks to save memory
  6729. var PIXELS_TO_PROCESS = 1048576;
  6730. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6731. for (var row = 0; row < height; row += chunkSize) {
  6732. var chunkHeight = Math.min(chunkSize, height - row);
  6733. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6734. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6735. if (hasBackdrop) {
  6736. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6737. }
  6738. composeFn(maskData.data, layerData.data, transferMap);
  6739. maskCtx.putImageData(layerData, 0, row);
  6740. }
  6741. }
  6742. function composeSMask(ctx, smask, layerCtx) {
  6743. var mask = smask.canvas;
  6744. var maskCtx = smask.context;
  6745. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6746. smask.offsetX, smask.offsetY);
  6747. var backdrop = smask.backdrop || null;
  6748. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6749. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6750. {subtype: smask.subtype, backdrop: backdrop});
  6751. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6752. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6753. return;
  6754. }
  6755. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6756. smask.subtype, backdrop, smask.transferMap);
  6757. ctx.drawImage(mask, 0, 0);
  6758. }
  6759. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6760. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6761. var NORMAL_CLIP = {};
  6762. var EO_CLIP = {};
  6763. CanvasGraphics.prototype = {
  6764. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6765. transparency) {
  6766. // For pdfs that use blend modes we have to clear the canvas else certain
  6767. // blend modes can look wrong since we'd be blending with a white
  6768. // backdrop. The problem with a transparent backdrop though is we then
  6769. // don't get sub pixel anti aliasing on text, creating temporary
  6770. // transparent canvas when we have blend modes.
  6771. var width = this.ctx.canvas.width;
  6772. var height = this.ctx.canvas.height;
  6773. this.ctx.save();
  6774. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6775. this.ctx.fillRect(0, 0, width, height);
  6776. this.ctx.restore();
  6777. if (transparency) {
  6778. var transparentCanvas = this.cachedCanvases.getCanvas(
  6779. 'transparent', width, height, true);
  6780. this.compositeCtx = this.ctx;
  6781. this.transparentCanvas = transparentCanvas.canvas;
  6782. this.ctx = transparentCanvas.context;
  6783. this.ctx.save();
  6784. // The transform can be applied before rendering, transferring it to
  6785. // the new canvas.
  6786. this.ctx.transform.apply(this.ctx,
  6787. this.compositeCtx.mozCurrentTransform);
  6788. }
  6789. this.ctx.save();
  6790. if (transform) {
  6791. this.ctx.transform.apply(this.ctx, transform);
  6792. }
  6793. this.ctx.transform.apply(this.ctx, viewport.transform);
  6794. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6795. if (this.imageLayer) {
  6796. this.imageLayer.beginLayout();
  6797. }
  6798. },
  6799. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6800. operatorList,
  6801. executionStartIdx, continueCallback,
  6802. stepper) {
  6803. var argsArray = operatorList.argsArray;
  6804. var fnArray = operatorList.fnArray;
  6805. var i = executionStartIdx || 0;
  6806. var argsArrayLen = argsArray.length;
  6807. // Sometimes the OperatorList to execute is empty.
  6808. if (argsArrayLen === i) {
  6809. return i;
  6810. }
  6811. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6812. typeof continueCallback === 'function');
  6813. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6814. var steps = 0;
  6815. var commonObjs = this.commonObjs;
  6816. var objs = this.objs;
  6817. var fnId;
  6818. while (true) {
  6819. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6820. stepper.breakIt(i, continueCallback);
  6821. return i;
  6822. }
  6823. fnId = fnArray[i];
  6824. if (fnId !== OPS.dependency) {
  6825. this[fnId].apply(this, argsArray[i]);
  6826. } else {
  6827. var deps = argsArray[i];
  6828. for (var n = 0, nn = deps.length; n < nn; n++) {
  6829. var depObjId = deps[n];
  6830. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6831. var objsPool = common ? commonObjs : objs;
  6832. // If the promise isn't resolved yet, add the continueCallback
  6833. // to the promise and bail out.
  6834. if (!objsPool.isResolved(depObjId)) {
  6835. objsPool.get(depObjId, continueCallback);
  6836. return i;
  6837. }
  6838. }
  6839. }
  6840. i++;
  6841. // If the entire operatorList was executed, stop as were done.
  6842. if (i === argsArrayLen) {
  6843. return i;
  6844. }
  6845. // If the execution took longer then a certain amount of time and
  6846. // `continueCallback` is specified, interrupt the execution.
  6847. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6848. if (Date.now() > endTime) {
  6849. continueCallback();
  6850. return i;
  6851. }
  6852. steps = 0;
  6853. }
  6854. // If the operatorList isn't executed completely yet OR the execution
  6855. // time was short enough, do another execution round.
  6856. }
  6857. },
  6858. endDrawing: function CanvasGraphics_endDrawing() {
  6859. // Finishing all opened operations such as SMask group painting.
  6860. if (this.current.activeSMask !== null) {
  6861. this.endSMaskGroup();
  6862. }
  6863. this.ctx.restore();
  6864. if (this.transparentCanvas) {
  6865. this.ctx = this.compositeCtx;
  6866. this.ctx.save();
  6867. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6868. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6869. this.ctx.restore();
  6870. this.transparentCanvas = null;
  6871. }
  6872. this.cachedCanvases.clear();
  6873. WebGLUtils.clear();
  6874. if (this.imageLayer) {
  6875. this.imageLayer.endLayout();
  6876. }
  6877. },
  6878. // Graphics state
  6879. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6880. this.current.lineWidth = width;
  6881. this.ctx.lineWidth = width;
  6882. },
  6883. setLineCap: function CanvasGraphics_setLineCap(style) {
  6884. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6885. },
  6886. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6887. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6888. },
  6889. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6890. this.ctx.miterLimit = limit;
  6891. },
  6892. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6893. var ctx = this.ctx;
  6894. if (ctx.setLineDash !== undefined) {
  6895. ctx.setLineDash(dashArray);
  6896. ctx.lineDashOffset = dashPhase;
  6897. }
  6898. },
  6899. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6900. // Maybe if we one day fully support color spaces this will be important
  6901. // for now we can ignore.
  6902. // TODO set rendering intent?
  6903. },
  6904. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6905. // There's no way to control this with canvas, but we can safely ignore.
  6906. // TODO set flatness?
  6907. },
  6908. setGState: function CanvasGraphics_setGState(states) {
  6909. for (var i = 0, ii = states.length; i < ii; i++) {
  6910. var state = states[i];
  6911. var key = state[0];
  6912. var value = state[1];
  6913. switch (key) {
  6914. case 'LW':
  6915. this.setLineWidth(value);
  6916. break;
  6917. case 'LC':
  6918. this.setLineCap(value);
  6919. break;
  6920. case 'LJ':
  6921. this.setLineJoin(value);
  6922. break;
  6923. case 'ML':
  6924. this.setMiterLimit(value);
  6925. break;
  6926. case 'D':
  6927. this.setDash(value[0], value[1]);
  6928. break;
  6929. case 'RI':
  6930. this.setRenderingIntent(value);
  6931. break;
  6932. case 'FL':
  6933. this.setFlatness(value);
  6934. break;
  6935. case 'Font':
  6936. this.setFont(value[0], value[1]);
  6937. break;
  6938. case 'CA':
  6939. this.current.strokeAlpha = state[1];
  6940. break;
  6941. case 'ca':
  6942. this.current.fillAlpha = state[1];
  6943. this.ctx.globalAlpha = state[1];
  6944. break;
  6945. case 'BM':
  6946. if (value && value.name && (value.name !== 'Normal')) {
  6947. var mode = value.name.replace(/([A-Z])/g,
  6948. function(c) {
  6949. return '-' + c.toLowerCase();
  6950. }
  6951. ).substring(1);
  6952. this.ctx.globalCompositeOperation = mode;
  6953. if (this.ctx.globalCompositeOperation !== mode) {
  6954. warn('globalCompositeOperation "' + mode +
  6955. '" is not supported');
  6956. }
  6957. } else {
  6958. this.ctx.globalCompositeOperation = 'source-over';
  6959. }
  6960. break;
  6961. case 'SMask':
  6962. if (this.current.activeSMask) {
  6963. // If SMask is currrenly used, it needs to be suspended or
  6964. // finished. Suspend only makes sense when at least one save()
  6965. // was performed and state needs to be reverted on restore().
  6966. if (this.stateStack.length > 0 &&
  6967. (this.stateStack[this.stateStack.length - 1].activeSMask ===
  6968. this.current.activeSMask)) {
  6969. this.suspendSMaskGroup();
  6970. } else {
  6971. this.endSMaskGroup();
  6972. }
  6973. }
  6974. this.current.activeSMask = value ? this.tempSMask : null;
  6975. if (this.current.activeSMask) {
  6976. this.beginSMaskGroup();
  6977. }
  6978. this.tempSMask = null;
  6979. break;
  6980. }
  6981. }
  6982. },
  6983. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6984. var activeSMask = this.current.activeSMask;
  6985. var drawnWidth = activeSMask.canvas.width;
  6986. var drawnHeight = activeSMask.canvas.height;
  6987. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6988. var scratchCanvas = this.cachedCanvases.getCanvas(
  6989. cacheId, drawnWidth, drawnHeight, true);
  6990. var currentCtx = this.ctx;
  6991. var currentTransform = currentCtx.mozCurrentTransform;
  6992. this.ctx.save();
  6993. var groupCtx = scratchCanvas.context;
  6994. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6995. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6996. groupCtx.transform.apply(groupCtx, currentTransform);
  6997. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6998. copyCtxState(currentCtx, groupCtx);
  6999. this.ctx = groupCtx;
  7000. this.setGState([
  7001. ['BM', 'Normal'],
  7002. ['ca', 1],
  7003. ['CA', 1]
  7004. ]);
  7005. this.groupStack.push(currentCtx);
  7006. this.groupLevel++;
  7007. },
  7008. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7009. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7010. // and future ctx state restored.
  7011. var groupCtx = this.ctx;
  7012. this.groupLevel--;
  7013. this.ctx = this.groupStack.pop();
  7014. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7015. this.ctx.restore();
  7016. this.ctx.save(); // save is needed since SMask will be resumed.
  7017. copyCtxState(groupCtx, this.ctx);
  7018. // Saving state for resuming.
  7019. this.current.resumeSMaskCtx = groupCtx;
  7020. // Transform was changed in the SMask canvas, reflecting this change on
  7021. // this.ctx.
  7022. var deltaTransform = Util.transform(
  7023. this.current.activeSMask.startTransformInverse,
  7024. groupCtx.mozCurrentTransform);
  7025. this.ctx.transform.apply(this.ctx, deltaTransform);
  7026. // SMask was composed, the results at the groupCtx can be cleared.
  7027. groupCtx.save();
  7028. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7029. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7030. groupCtx.restore();
  7031. },
  7032. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7033. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7034. // any groupCtx state since restore() command (the only caller) will do
  7035. // that for us. See also beginSMaskGroup.
  7036. var groupCtx = this.current.resumeSMaskCtx;
  7037. var currentCtx = this.ctx;
  7038. this.ctx = groupCtx;
  7039. this.groupStack.push(currentCtx);
  7040. this.groupLevel++;
  7041. },
  7042. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7043. var groupCtx = this.ctx;
  7044. this.groupLevel--;
  7045. this.ctx = this.groupStack.pop();
  7046. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7047. this.ctx.restore();
  7048. copyCtxState(groupCtx, this.ctx);
  7049. // Transform was changed in the SMask canvas, reflecting this change on
  7050. // this.ctx.
  7051. var deltaTransform = Util.transform(
  7052. this.current.activeSMask.startTransformInverse,
  7053. groupCtx.mozCurrentTransform);
  7054. this.ctx.transform.apply(this.ctx, deltaTransform);
  7055. },
  7056. save: function CanvasGraphics_save() {
  7057. this.ctx.save();
  7058. var old = this.current;
  7059. this.stateStack.push(old);
  7060. this.current = old.clone();
  7061. this.current.resumeSMaskCtx = null;
  7062. },
  7063. restore: function CanvasGraphics_restore() {
  7064. // SMask was suspended, we just need to resume it.
  7065. if (this.current.resumeSMaskCtx) {
  7066. this.resumeSMaskGroup();
  7067. }
  7068. // SMask has to be finished once there is no states that are using the
  7069. // same SMask.
  7070. if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
  7071. this.stateStack[this.stateStack.length - 1].activeSMask !==
  7072. this.current.activeSMask)) {
  7073. this.endSMaskGroup();
  7074. }
  7075. if (this.stateStack.length !== 0) {
  7076. this.current = this.stateStack.pop();
  7077. this.ctx.restore();
  7078. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7079. this.pendingClip = null;
  7080. this.cachedGetSinglePixelWidth = null;
  7081. }
  7082. },
  7083. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7084. this.ctx.transform(a, b, c, d, e, f);
  7085. this.cachedGetSinglePixelWidth = null;
  7086. },
  7087. // Path
  7088. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7089. var ctx = this.ctx;
  7090. var current = this.current;
  7091. var x = current.x, y = current.y;
  7092. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7093. switch (ops[i] | 0) {
  7094. case OPS.rectangle:
  7095. x = args[j++];
  7096. y = args[j++];
  7097. var width = args[j++];
  7098. var height = args[j++];
  7099. if (width === 0) {
  7100. width = this.getSinglePixelWidth();
  7101. }
  7102. if (height === 0) {
  7103. height = this.getSinglePixelWidth();
  7104. }
  7105. var xw = x + width;
  7106. var yh = y + height;
  7107. this.ctx.moveTo(x, y);
  7108. this.ctx.lineTo(xw, y);
  7109. this.ctx.lineTo(xw, yh);
  7110. this.ctx.lineTo(x, yh);
  7111. this.ctx.lineTo(x, y);
  7112. this.ctx.closePath();
  7113. break;
  7114. case OPS.moveTo:
  7115. x = args[j++];
  7116. y = args[j++];
  7117. ctx.moveTo(x, y);
  7118. break;
  7119. case OPS.lineTo:
  7120. x = args[j++];
  7121. y = args[j++];
  7122. ctx.lineTo(x, y);
  7123. break;
  7124. case OPS.curveTo:
  7125. x = args[j + 4];
  7126. y = args[j + 5];
  7127. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  7128. x, y);
  7129. j += 6;
  7130. break;
  7131. case OPS.curveTo2:
  7132. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  7133. args[j + 2], args[j + 3]);
  7134. x = args[j + 2];
  7135. y = args[j + 3];
  7136. j += 4;
  7137. break;
  7138. case OPS.curveTo3:
  7139. x = args[j + 2];
  7140. y = args[j + 3];
  7141. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7142. j += 4;
  7143. break;
  7144. case OPS.closePath:
  7145. ctx.closePath();
  7146. break;
  7147. }
  7148. }
  7149. current.setCurrentPoint(x, y);
  7150. },
  7151. closePath: function CanvasGraphics_closePath() {
  7152. this.ctx.closePath();
  7153. },
  7154. stroke: function CanvasGraphics_stroke(consumePath) {
  7155. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7156. var ctx = this.ctx;
  7157. var strokeColor = this.current.strokeColor;
  7158. // Prevent drawing too thin lines by enforcing a minimum line width.
  7159. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  7160. this.current.lineWidth);
  7161. // For stroke we want to temporarily change the global alpha to the
  7162. // stroking alpha.
  7163. ctx.globalAlpha = this.current.strokeAlpha;
  7164. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  7165. strokeColor.type === 'Pattern') {
  7166. // for patterns, we transform to pattern space, calculate
  7167. // the pattern, call stroke, and restore to user space
  7168. ctx.save();
  7169. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7170. ctx.stroke();
  7171. ctx.restore();
  7172. } else {
  7173. ctx.stroke();
  7174. }
  7175. if (consumePath) {
  7176. this.consumePath();
  7177. }
  7178. // Restore the global alpha to the fill alpha
  7179. ctx.globalAlpha = this.current.fillAlpha;
  7180. },
  7181. closeStroke: function CanvasGraphics_closeStroke() {
  7182. this.closePath();
  7183. this.stroke();
  7184. },
  7185. fill: function CanvasGraphics_fill(consumePath) {
  7186. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7187. var ctx = this.ctx;
  7188. var fillColor = this.current.fillColor;
  7189. var isPatternFill = this.current.patternFill;
  7190. var needRestore = false;
  7191. if (isPatternFill) {
  7192. ctx.save();
  7193. if (this.baseTransform) {
  7194. ctx.setTransform.apply(ctx, this.baseTransform);
  7195. }
  7196. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7197. needRestore = true;
  7198. }
  7199. if (this.pendingEOFill) {
  7200. if (ctx.mozFillRule !== undefined) {
  7201. ctx.mozFillRule = 'evenodd';
  7202. ctx.fill();
  7203. ctx.mozFillRule = 'nonzero';
  7204. } else {
  7205. ctx.fill('evenodd');
  7206. }
  7207. this.pendingEOFill = false;
  7208. } else {
  7209. ctx.fill();
  7210. }
  7211. if (needRestore) {
  7212. ctx.restore();
  7213. }
  7214. if (consumePath) {
  7215. this.consumePath();
  7216. }
  7217. },
  7218. eoFill: function CanvasGraphics_eoFill() {
  7219. this.pendingEOFill = true;
  7220. this.fill();
  7221. },
  7222. fillStroke: function CanvasGraphics_fillStroke() {
  7223. this.fill(false);
  7224. this.stroke(false);
  7225. this.consumePath();
  7226. },
  7227. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7228. this.pendingEOFill = true;
  7229. this.fillStroke();
  7230. },
  7231. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7232. this.closePath();
  7233. this.fillStroke();
  7234. },
  7235. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7236. this.pendingEOFill = true;
  7237. this.closePath();
  7238. this.fillStroke();
  7239. },
  7240. endPath: function CanvasGraphics_endPath() {
  7241. this.consumePath();
  7242. },
  7243. // Clipping
  7244. clip: function CanvasGraphics_clip() {
  7245. this.pendingClip = NORMAL_CLIP;
  7246. },
  7247. eoClip: function CanvasGraphics_eoClip() {
  7248. this.pendingClip = EO_CLIP;
  7249. },
  7250. // Text
  7251. beginText: function CanvasGraphics_beginText() {
  7252. this.current.textMatrix = IDENTITY_MATRIX;
  7253. this.current.textMatrixScale = 1;
  7254. this.current.x = this.current.lineX = 0;
  7255. this.current.y = this.current.lineY = 0;
  7256. },
  7257. endText: function CanvasGraphics_endText() {
  7258. var paths = this.pendingTextPaths;
  7259. var ctx = this.ctx;
  7260. if (paths === undefined) {
  7261. ctx.beginPath();
  7262. return;
  7263. }
  7264. ctx.save();
  7265. ctx.beginPath();
  7266. for (var i = 0; i < paths.length; i++) {
  7267. var path = paths[i];
  7268. ctx.setTransform.apply(ctx, path.transform);
  7269. ctx.translate(path.x, path.y);
  7270. path.addToPath(ctx, path.fontSize);
  7271. }
  7272. ctx.restore();
  7273. ctx.clip();
  7274. ctx.beginPath();
  7275. delete this.pendingTextPaths;
  7276. },
  7277. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7278. this.current.charSpacing = spacing;
  7279. },
  7280. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7281. this.current.wordSpacing = spacing;
  7282. },
  7283. setHScale: function CanvasGraphics_setHScale(scale) {
  7284. this.current.textHScale = scale / 100;
  7285. },
  7286. setLeading: function CanvasGraphics_setLeading(leading) {
  7287. this.current.leading = -leading;
  7288. },
  7289. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7290. var fontObj = this.commonObjs.get(fontRefName);
  7291. var current = this.current;
  7292. if (!fontObj) {
  7293. error('Can\'t find font for ' + fontRefName);
  7294. }
  7295. current.fontMatrix = (fontObj.fontMatrix ?
  7296. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7297. // A valid matrix needs all main diagonal elements to be non-zero
  7298. // This also ensures we bypass FF bugzilla bug #719844.
  7299. if (current.fontMatrix[0] === 0 ||
  7300. current.fontMatrix[3] === 0) {
  7301. warn('Invalid font matrix for font ' + fontRefName);
  7302. }
  7303. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7304. // and in some docs this can be negative (inverted x-y axes).
  7305. if (size < 0) {
  7306. size = -size;
  7307. current.fontDirection = -1;
  7308. } else {
  7309. current.fontDirection = 1;
  7310. }
  7311. this.current.font = fontObj;
  7312. this.current.fontSize = size;
  7313. if (fontObj.isType3Font) {
  7314. return; // we don't need ctx.font for Type3 fonts
  7315. }
  7316. var name = fontObj.loadedName || 'sans-serif';
  7317. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  7318. (fontObj.bold ? 'bold' : 'normal');
  7319. var italic = fontObj.italic ? 'italic' : 'normal';
  7320. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7321. // Some font backends cannot handle fonts below certain size.
  7322. // Keeping the font at minimal size and using the fontSizeScale to change
  7323. // the current transformation matrix before the fillText/strokeText.
  7324. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7325. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  7326. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7327. this.current.fontSizeScale = size / browserFontSize;
  7328. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7329. this.ctx.font = rule;
  7330. },
  7331. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7332. this.current.textRenderingMode = mode;
  7333. },
  7334. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7335. this.current.textRise = rise;
  7336. },
  7337. moveText: function CanvasGraphics_moveText(x, y) {
  7338. this.current.x = this.current.lineX += x;
  7339. this.current.y = this.current.lineY += y;
  7340. },
  7341. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7342. this.setLeading(-y);
  7343. this.moveText(x, y);
  7344. },
  7345. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7346. this.current.textMatrix = [a, b, c, d, e, f];
  7347. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7348. this.current.x = this.current.lineX = 0;
  7349. this.current.y = this.current.lineY = 0;
  7350. },
  7351. nextLine: function CanvasGraphics_nextLine() {
  7352. this.moveText(0, this.current.leading);
  7353. },
  7354. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7355. var ctx = this.ctx;
  7356. var current = this.current;
  7357. var font = current.font;
  7358. var textRenderingMode = current.textRenderingMode;
  7359. var fontSize = current.fontSize / current.fontSizeScale;
  7360. var fillStrokeMode = textRenderingMode &
  7361. TextRenderingMode.FILL_STROKE_MASK;
  7362. var isAddToPathSet = !!(textRenderingMode &
  7363. TextRenderingMode.ADD_TO_PATH_FLAG);
  7364. var addToPath;
  7365. if (font.disableFontFace || isAddToPathSet) {
  7366. addToPath = font.getPathGenerator(this.commonObjs, character);
  7367. }
  7368. if (font.disableFontFace) {
  7369. ctx.save();
  7370. ctx.translate(x, y);
  7371. ctx.beginPath();
  7372. addToPath(ctx, fontSize);
  7373. if (fillStrokeMode === TextRenderingMode.FILL ||
  7374. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7375. ctx.fill();
  7376. }
  7377. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7378. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7379. ctx.stroke();
  7380. }
  7381. ctx.restore();
  7382. } else {
  7383. if (fillStrokeMode === TextRenderingMode.FILL ||
  7384. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7385. ctx.fillText(character, x, y);
  7386. }
  7387. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7388. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7389. ctx.strokeText(character, x, y);
  7390. }
  7391. }
  7392. if (isAddToPathSet) {
  7393. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7394. paths.push({
  7395. transform: ctx.mozCurrentTransform,
  7396. x: x,
  7397. y: y,
  7398. fontSize: fontSize,
  7399. addToPath: addToPath
  7400. });
  7401. }
  7402. },
  7403. get isFontSubpixelAAEnabled() {
  7404. // Checks if anti-aliasing is enabled when scaled text is painted.
  7405. // On Windows GDI scaled fonts looks bad.
  7406. var ctx = document.createElement('canvas').getContext('2d');
  7407. ctx.scale(1.5, 1);
  7408. ctx.fillText('I', 0, 10);
  7409. var data = ctx.getImageData(0, 0, 10, 10).data;
  7410. var enabled = false;
  7411. for (var i = 3; i < data.length; i += 4) {
  7412. if (data[i] > 0 && data[i] < 255) {
  7413. enabled = true;
  7414. break;
  7415. }
  7416. }
  7417. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7418. },
  7419. showText: function CanvasGraphics_showText(glyphs) {
  7420. var current = this.current;
  7421. var font = current.font;
  7422. if (font.isType3Font) {
  7423. return this.showType3Text(glyphs);
  7424. }
  7425. var fontSize = current.fontSize;
  7426. if (fontSize === 0) {
  7427. return;
  7428. }
  7429. var ctx = this.ctx;
  7430. var fontSizeScale = current.fontSizeScale;
  7431. var charSpacing = current.charSpacing;
  7432. var wordSpacing = current.wordSpacing;
  7433. var fontDirection = current.fontDirection;
  7434. var textHScale = current.textHScale * fontDirection;
  7435. var glyphsLength = glyphs.length;
  7436. var vertical = font.vertical;
  7437. var spacingDir = vertical ? 1 : -1;
  7438. var defaultVMetrics = font.defaultVMetrics;
  7439. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7440. var simpleFillText =
  7441. current.textRenderingMode === TextRenderingMode.FILL &&
  7442. !font.disableFontFace;
  7443. ctx.save();
  7444. ctx.transform.apply(ctx, current.textMatrix);
  7445. ctx.translate(current.x, current.y + current.textRise);
  7446. if (current.patternFill) {
  7447. // TODO: Some shading patterns are not applied correctly to text,
  7448. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7449. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7450. }
  7451. if (fontDirection > 0) {
  7452. ctx.scale(textHScale, -1);
  7453. } else {
  7454. ctx.scale(textHScale, 1);
  7455. }
  7456. var lineWidth = current.lineWidth;
  7457. var scale = current.textMatrixScale;
  7458. if (scale === 0 || lineWidth === 0) {
  7459. var fillStrokeMode = current.textRenderingMode &
  7460. TextRenderingMode.FILL_STROKE_MASK;
  7461. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7462. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7463. this.cachedGetSinglePixelWidth = null;
  7464. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7465. }
  7466. } else {
  7467. lineWidth /= scale;
  7468. }
  7469. if (fontSizeScale !== 1.0) {
  7470. ctx.scale(fontSizeScale, fontSizeScale);
  7471. lineWidth /= fontSizeScale;
  7472. }
  7473. ctx.lineWidth = lineWidth;
  7474. var x = 0, i;
  7475. for (i = 0; i < glyphsLength; ++i) {
  7476. var glyph = glyphs[i];
  7477. if (isNum(glyph)) {
  7478. x += spacingDir * glyph * fontSize / 1000;
  7479. continue;
  7480. }
  7481. var restoreNeeded = false;
  7482. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7483. var character = glyph.fontChar;
  7484. var accent = glyph.accent;
  7485. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7486. var width = glyph.width;
  7487. if (vertical) {
  7488. var vmetric, vx, vy;
  7489. vmetric = glyph.vmetric || defaultVMetrics;
  7490. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7491. vx = -vx * widthAdvanceScale;
  7492. vy = vmetric[2] * widthAdvanceScale;
  7493. width = vmetric ? -vmetric[0] : width;
  7494. scaledX = vx / fontSizeScale;
  7495. scaledY = (x + vy) / fontSizeScale;
  7496. } else {
  7497. scaledX = x / fontSizeScale;
  7498. scaledY = 0;
  7499. }
  7500. if (font.remeasure && width > 0) {
  7501. // Some standard fonts may not have the exact width: rescale per
  7502. // character if measured width is greater than expected glyph width
  7503. // and subpixel-aa is enabled, otherwise just center the glyph.
  7504. var measuredWidth = ctx.measureText(character).width * 1000 /
  7505. fontSize * fontSizeScale;
  7506. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7507. var characterScaleX = width / measuredWidth;
  7508. restoreNeeded = true;
  7509. ctx.save();
  7510. ctx.scale(characterScaleX, 1);
  7511. scaledX /= characterScaleX;
  7512. } else if (width !== measuredWidth) {
  7513. scaledX += (width - measuredWidth) / 2000 *
  7514. fontSize / fontSizeScale;
  7515. }
  7516. }
  7517. // Only attempt to draw the glyph if it is actually in the embedded font
  7518. // file or if there isn't a font file so the fallback font is shown.
  7519. if (glyph.isInFont || font.missingFile) {
  7520. if (simpleFillText && !accent) {
  7521. // common case
  7522. ctx.fillText(character, scaledX, scaledY);
  7523. } else {
  7524. this.paintChar(character, scaledX, scaledY);
  7525. if (accent) {
  7526. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7527. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7528. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7529. }
  7530. }
  7531. }
  7532. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7533. x += charWidth;
  7534. if (restoreNeeded) {
  7535. ctx.restore();
  7536. }
  7537. }
  7538. if (vertical) {
  7539. current.y -= x * textHScale;
  7540. } else {
  7541. current.x += x * textHScale;
  7542. }
  7543. ctx.restore();
  7544. },
  7545. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7546. // Type3 fonts - each glyph is a "mini-PDF"
  7547. var ctx = this.ctx;
  7548. var current = this.current;
  7549. var font = current.font;
  7550. var fontSize = current.fontSize;
  7551. var fontDirection = current.fontDirection;
  7552. var spacingDir = font.vertical ? 1 : -1;
  7553. var charSpacing = current.charSpacing;
  7554. var wordSpacing = current.wordSpacing;
  7555. var textHScale = current.textHScale * fontDirection;
  7556. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7557. var glyphsLength = glyphs.length;
  7558. var isTextInvisible =
  7559. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7560. var i, glyph, width, spacingLength;
  7561. if (isTextInvisible || fontSize === 0) {
  7562. return;
  7563. }
  7564. this.cachedGetSinglePixelWidth = null;
  7565. ctx.save();
  7566. ctx.transform.apply(ctx, current.textMatrix);
  7567. ctx.translate(current.x, current.y);
  7568. ctx.scale(textHScale, fontDirection);
  7569. for (i = 0; i < glyphsLength; ++i) {
  7570. glyph = glyphs[i];
  7571. if (isNum(glyph)) {
  7572. spacingLength = spacingDir * glyph * fontSize / 1000;
  7573. this.ctx.translate(spacingLength, 0);
  7574. current.x += spacingLength * textHScale;
  7575. continue;
  7576. }
  7577. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7578. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7579. if (!operatorList) {
  7580. warn('Type3 character \"' + glyph.operatorListId +
  7581. '\" is not available');
  7582. continue;
  7583. }
  7584. this.processingType3 = glyph;
  7585. this.save();
  7586. ctx.scale(fontSize, fontSize);
  7587. ctx.transform.apply(ctx, fontMatrix);
  7588. this.executeOperatorList(operatorList);
  7589. this.restore();
  7590. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7591. width = transformed[0] * fontSize + spacing;
  7592. ctx.translate(width, 0);
  7593. current.x += width * textHScale;
  7594. }
  7595. ctx.restore();
  7596. this.processingType3 = null;
  7597. },
  7598. // Type3 fonts
  7599. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7600. // We can safely ignore this since the width should be the same
  7601. // as the width in the Widths array.
  7602. },
  7603. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  7604. yWidth,
  7605. llx,
  7606. lly,
  7607. urx,
  7608. ury) {
  7609. // TODO According to the spec we're also suppose to ignore any operators
  7610. // that set color or include images while processing this type3 font.
  7611. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7612. this.clip();
  7613. this.endPath();
  7614. },
  7615. // Color
  7616. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7617. var pattern;
  7618. if (IR[0] === 'TilingPattern') {
  7619. var color = IR[1];
  7620. var baseTransform = this.baseTransform ||
  7621. this.ctx.mozCurrentTransform.slice();
  7622. var self = this;
  7623. var canvasGraphicsFactory = {
  7624. createCanvasGraphics: function (ctx) {
  7625. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7626. }
  7627. };
  7628. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  7629. baseTransform);
  7630. } else {
  7631. pattern = getShadingPatternFromIR(IR);
  7632. }
  7633. return pattern;
  7634. },
  7635. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  7636. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7637. },
  7638. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  7639. this.current.fillColor = this.getColorN_Pattern(arguments);
  7640. this.current.patternFill = true;
  7641. },
  7642. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7643. var color = Util.makeCssRgb(r, g, b);
  7644. this.ctx.strokeStyle = color;
  7645. this.current.strokeColor = color;
  7646. },
  7647. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7648. var color = Util.makeCssRgb(r, g, b);
  7649. this.ctx.fillStyle = color;
  7650. this.current.fillColor = color;
  7651. this.current.patternFill = false;
  7652. },
  7653. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7654. var ctx = this.ctx;
  7655. this.save();
  7656. var pattern = getShadingPatternFromIR(patternIR);
  7657. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7658. var inv = ctx.mozCurrentTransformInverse;
  7659. if (inv) {
  7660. var canvas = ctx.canvas;
  7661. var width = canvas.width;
  7662. var height = canvas.height;
  7663. var bl = Util.applyTransform([0, 0], inv);
  7664. var br = Util.applyTransform([0, height], inv);
  7665. var ul = Util.applyTransform([width, 0], inv);
  7666. var ur = Util.applyTransform([width, height], inv);
  7667. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7668. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7669. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7670. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7671. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7672. } else {
  7673. // HACK to draw the gradient onto an infinite rectangle.
  7674. // PDF gradients are drawn across the entire image while
  7675. // Canvas only allows gradients to be drawn in a rectangle
  7676. // The following bug should allow us to remove this.
  7677. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7678. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7679. }
  7680. this.restore();
  7681. },
  7682. // Images
  7683. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7684. error('Should not call beginInlineImage');
  7685. },
  7686. beginImageData: function CanvasGraphics_beginImageData() {
  7687. error('Should not call beginImageData');
  7688. },
  7689. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7690. bbox) {
  7691. this.save();
  7692. this.baseTransformStack.push(this.baseTransform);
  7693. if (isArray(matrix) && 6 === matrix.length) {
  7694. this.transform.apply(this, matrix);
  7695. }
  7696. this.baseTransform = this.ctx.mozCurrentTransform;
  7697. if (isArray(bbox) && 4 === bbox.length) {
  7698. var width = bbox[2] - bbox[0];
  7699. var height = bbox[3] - bbox[1];
  7700. this.ctx.rect(bbox[0], bbox[1], width, height);
  7701. this.clip();
  7702. this.endPath();
  7703. }
  7704. },
  7705. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7706. this.restore();
  7707. this.baseTransform = this.baseTransformStack.pop();
  7708. },
  7709. beginGroup: function CanvasGraphics_beginGroup(group) {
  7710. this.save();
  7711. var currentCtx = this.ctx;
  7712. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7713. // group results aren't usually that different and they even have tools
  7714. // that ignore this setting. Notes from Rik on implementing:
  7715. // - When you encounter an transparency group, create a new canvas with
  7716. // the dimensions of the bbox
  7717. // - copy the content from the previous canvas to the new canvas
  7718. // - draw as usual
  7719. // - remove the backdrop alpha:
  7720. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7721. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7722. // backdrop
  7723. // - remove background color:
  7724. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7725. if (!group.isolated) {
  7726. info('TODO: Support non-isolated groups.');
  7727. }
  7728. // TODO knockout - supposedly possible with the clever use of compositing
  7729. // modes.
  7730. if (group.knockout) {
  7731. warn('Knockout groups not supported.');
  7732. }
  7733. var currentTransform = currentCtx.mozCurrentTransform;
  7734. if (group.matrix) {
  7735. currentCtx.transform.apply(currentCtx, group.matrix);
  7736. }
  7737. assert(group.bbox, 'Bounding box is required.');
  7738. // Based on the current transform figure out how big the bounding box
  7739. // will actually be.
  7740. var bounds = Util.getAxialAlignedBoundingBox(
  7741. group.bbox,
  7742. currentCtx.mozCurrentTransform);
  7743. // Clip the bounding box to the current canvas.
  7744. var canvasBounds = [0,
  7745. 0,
  7746. currentCtx.canvas.width,
  7747. currentCtx.canvas.height];
  7748. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7749. // Use ceil in case we're between sizes so we don't create canvas that is
  7750. // too small and make the canvas at least 1x1 pixels.
  7751. var offsetX = Math.floor(bounds[0]);
  7752. var offsetY = Math.floor(bounds[1]);
  7753. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7754. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7755. var scaleX = 1, scaleY = 1;
  7756. if (drawnWidth > MAX_GROUP_SIZE) {
  7757. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7758. drawnWidth = MAX_GROUP_SIZE;
  7759. }
  7760. if (drawnHeight > MAX_GROUP_SIZE) {
  7761. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7762. drawnHeight = MAX_GROUP_SIZE;
  7763. }
  7764. var cacheId = 'groupAt' + this.groupLevel;
  7765. if (group.smask) {
  7766. // Using two cache entries is case if masks are used one after another.
  7767. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7768. }
  7769. var scratchCanvas = this.cachedCanvases.getCanvas(
  7770. cacheId, drawnWidth, drawnHeight, true);
  7771. var groupCtx = scratchCanvas.context;
  7772. // Since we created a new canvas that is just the size of the bounding box
  7773. // we have to translate the group ctx.
  7774. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7775. groupCtx.translate(-offsetX, -offsetY);
  7776. groupCtx.transform.apply(groupCtx, currentTransform);
  7777. if (group.smask) {
  7778. // Saving state and cached mask to be used in setGState.
  7779. this.smaskStack.push({
  7780. canvas: scratchCanvas.canvas,
  7781. context: groupCtx,
  7782. offsetX: offsetX,
  7783. offsetY: offsetY,
  7784. scaleX: scaleX,
  7785. scaleY: scaleY,
  7786. subtype: group.smask.subtype,
  7787. backdrop: group.smask.backdrop,
  7788. transferMap: group.smask.transferMap || null,
  7789. startTransformInverse: null, // used during suspend operation
  7790. });
  7791. } else {
  7792. // Setup the current ctx so when the group is popped we draw it at the
  7793. // right location.
  7794. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7795. currentCtx.translate(offsetX, offsetY);
  7796. currentCtx.scale(scaleX, scaleY);
  7797. }
  7798. // The transparency group inherits all off the current graphics state
  7799. // except the blend mode, soft mask, and alpha constants.
  7800. copyCtxState(currentCtx, groupCtx);
  7801. this.ctx = groupCtx;
  7802. this.setGState([
  7803. ['BM', 'Normal'],
  7804. ['ca', 1],
  7805. ['CA', 1]
  7806. ]);
  7807. this.groupStack.push(currentCtx);
  7808. this.groupLevel++;
  7809. // Reseting mask state, masks will be applied on restore of the group.
  7810. this.current.activeSMask = null;
  7811. },
  7812. endGroup: function CanvasGraphics_endGroup(group) {
  7813. this.groupLevel--;
  7814. var groupCtx = this.ctx;
  7815. this.ctx = this.groupStack.pop();
  7816. // Turn off image smoothing to avoid sub pixel interpolation which can
  7817. // look kind of blurry for some pdfs.
  7818. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7819. this.ctx.imageSmoothingEnabled = false;
  7820. } else {
  7821. this.ctx.mozImageSmoothingEnabled = false;
  7822. }
  7823. if (group.smask) {
  7824. this.tempSMask = this.smaskStack.pop();
  7825. } else {
  7826. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7827. }
  7828. this.restore();
  7829. },
  7830. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7831. this.save();
  7832. this.current = new CanvasExtraState();
  7833. if (this.baseTransform) {
  7834. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7835. }
  7836. },
  7837. endAnnotations: function CanvasGraphics_endAnnotations() {
  7838. this.restore();
  7839. },
  7840. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7841. matrix) {
  7842. this.save();
  7843. if (isArray(rect) && 4 === rect.length) {
  7844. var width = rect[2] - rect[0];
  7845. var height = rect[3] - rect[1];
  7846. this.ctx.rect(rect[0], rect[1], width, height);
  7847. this.clip();
  7848. this.endPath();
  7849. }
  7850. this.transform.apply(this, transform);
  7851. this.transform.apply(this, matrix);
  7852. },
  7853. endAnnotation: function CanvasGraphics_endAnnotation() {
  7854. this.restore();
  7855. },
  7856. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7857. var domImage = this.objs.get(objId);
  7858. if (!domImage) {
  7859. warn('Dependent image isn\'t ready yet');
  7860. return;
  7861. }
  7862. this.save();
  7863. var ctx = this.ctx;
  7864. // scale the image to the unit square
  7865. ctx.scale(1 / w, -1 / h);
  7866. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7867. 0, -h, w, h);
  7868. if (this.imageLayer) {
  7869. var currentTransform = ctx.mozCurrentTransformInverse;
  7870. var position = this.getCanvasPosition(0, 0);
  7871. this.imageLayer.appendImage({
  7872. objId: objId,
  7873. left: position[0],
  7874. top: position[1],
  7875. width: w / currentTransform[0],
  7876. height: h / currentTransform[3]
  7877. });
  7878. }
  7879. this.restore();
  7880. },
  7881. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7882. var ctx = this.ctx;
  7883. var width = img.width, height = img.height;
  7884. var fillColor = this.current.fillColor;
  7885. var isPatternFill = this.current.patternFill;
  7886. var glyph = this.processingType3;
  7887. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7888. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7889. glyph.compiled =
  7890. compileType3Glyph({data: img.data, width: width, height: height});
  7891. } else {
  7892. glyph.compiled = null;
  7893. }
  7894. }
  7895. if (glyph && glyph.compiled) {
  7896. glyph.compiled(ctx);
  7897. return;
  7898. }
  7899. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7900. width, height);
  7901. var maskCtx = maskCanvas.context;
  7902. maskCtx.save();
  7903. putBinaryImageMask(maskCtx, img);
  7904. maskCtx.globalCompositeOperation = 'source-in';
  7905. maskCtx.fillStyle = isPatternFill ?
  7906. fillColor.getPattern(maskCtx, this) : fillColor;
  7907. maskCtx.fillRect(0, 0, width, height);
  7908. maskCtx.restore();
  7909. this.paintInlineImageXObject(maskCanvas.canvas);
  7910. },
  7911. paintImageMaskXObjectRepeat:
  7912. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7913. scaleY, positions) {
  7914. var width = imgData.width;
  7915. var height = imgData.height;
  7916. var fillColor = this.current.fillColor;
  7917. var isPatternFill = this.current.patternFill;
  7918. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7919. width, height);
  7920. var maskCtx = maskCanvas.context;
  7921. maskCtx.save();
  7922. putBinaryImageMask(maskCtx, imgData);
  7923. maskCtx.globalCompositeOperation = 'source-in';
  7924. maskCtx.fillStyle = isPatternFill ?
  7925. fillColor.getPattern(maskCtx, this) : fillColor;
  7926. maskCtx.fillRect(0, 0, width, height);
  7927. maskCtx.restore();
  7928. var ctx = this.ctx;
  7929. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7930. ctx.save();
  7931. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7932. ctx.scale(1, -1);
  7933. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7934. 0, -1, 1, 1);
  7935. ctx.restore();
  7936. }
  7937. },
  7938. paintImageMaskXObjectGroup:
  7939. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7940. var ctx = this.ctx;
  7941. var fillColor = this.current.fillColor;
  7942. var isPatternFill = this.current.patternFill;
  7943. for (var i = 0, ii = images.length; i < ii; i++) {
  7944. var image = images[i];
  7945. var width = image.width, height = image.height;
  7946. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7947. width, height);
  7948. var maskCtx = maskCanvas.context;
  7949. maskCtx.save();
  7950. putBinaryImageMask(maskCtx, image);
  7951. maskCtx.globalCompositeOperation = 'source-in';
  7952. maskCtx.fillStyle = isPatternFill ?
  7953. fillColor.getPattern(maskCtx, this) : fillColor;
  7954. maskCtx.fillRect(0, 0, width, height);
  7955. maskCtx.restore();
  7956. ctx.save();
  7957. ctx.transform.apply(ctx, image.transform);
  7958. ctx.scale(1, -1);
  7959. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7960. 0, -1, 1, 1);
  7961. ctx.restore();
  7962. }
  7963. },
  7964. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7965. var imgData = this.objs.get(objId);
  7966. if (!imgData) {
  7967. warn('Dependent image isn\'t ready yet');
  7968. return;
  7969. }
  7970. this.paintInlineImageXObject(imgData);
  7971. },
  7972. paintImageXObjectRepeat:
  7973. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7974. positions) {
  7975. var imgData = this.objs.get(objId);
  7976. if (!imgData) {
  7977. warn('Dependent image isn\'t ready yet');
  7978. return;
  7979. }
  7980. var width = imgData.width;
  7981. var height = imgData.height;
  7982. var map = [];
  7983. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7984. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7985. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7986. }
  7987. this.paintInlineImageXObjectGroup(imgData, map);
  7988. },
  7989. paintInlineImageXObject:
  7990. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7991. var width = imgData.width;
  7992. var height = imgData.height;
  7993. var ctx = this.ctx;
  7994. this.save();
  7995. // scale the image to the unit square
  7996. ctx.scale(1 / width, -1 / height);
  7997. var currentTransform = ctx.mozCurrentTransformInverse;
  7998. var a = currentTransform[0], b = currentTransform[1];
  7999. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  8000. var c = currentTransform[2], d = currentTransform[3];
  8001. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  8002. var imgToPaint, tmpCanvas;
  8003. // instanceof HTMLElement does not work in jsdom node.js module
  8004. if (imgData instanceof HTMLElement || !imgData.data) {
  8005. imgToPaint = imgData;
  8006. } else {
  8007. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  8008. width, height);
  8009. var tmpCtx = tmpCanvas.context;
  8010. putBinaryImageData(tmpCtx, imgData);
  8011. imgToPaint = tmpCanvas.canvas;
  8012. }
  8013. var paintWidth = width, paintHeight = height;
  8014. var tmpCanvasId = 'prescale1';
  8015. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8016. // pixels during drawImage operation, painting on the temporary canvas(es)
  8017. // that are twice smaller in size
  8018. while ((widthScale > 2 && paintWidth > 1) ||
  8019. (heightScale > 2 && paintHeight > 1)) {
  8020. var newWidth = paintWidth, newHeight = paintHeight;
  8021. if (widthScale > 2 && paintWidth > 1) {
  8022. newWidth = Math.ceil(paintWidth / 2);
  8023. widthScale /= paintWidth / newWidth;
  8024. }
  8025. if (heightScale > 2 && paintHeight > 1) {
  8026. newHeight = Math.ceil(paintHeight / 2);
  8027. heightScale /= paintHeight / newHeight;
  8028. }
  8029. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  8030. newWidth, newHeight);
  8031. tmpCtx = tmpCanvas.context;
  8032. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8033. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  8034. 0, 0, newWidth, newHeight);
  8035. imgToPaint = tmpCanvas.canvas;
  8036. paintWidth = newWidth;
  8037. paintHeight = newHeight;
  8038. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8039. }
  8040. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  8041. 0, -height, width, height);
  8042. if (this.imageLayer) {
  8043. var position = this.getCanvasPosition(0, -height);
  8044. this.imageLayer.appendImage({
  8045. imgData: imgData,
  8046. left: position[0],
  8047. top: position[1],
  8048. width: width / currentTransform[0],
  8049. height: height / currentTransform[3]
  8050. });
  8051. }
  8052. this.restore();
  8053. },
  8054. paintInlineImageXObjectGroup:
  8055. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8056. var ctx = this.ctx;
  8057. var w = imgData.width;
  8058. var h = imgData.height;
  8059. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8060. var tmpCtx = tmpCanvas.context;
  8061. putBinaryImageData(tmpCtx, imgData);
  8062. for (var i = 0, ii = map.length; i < ii; i++) {
  8063. var entry = map[i];
  8064. ctx.save();
  8065. ctx.transform.apply(ctx, entry.transform);
  8066. ctx.scale(1, -1);
  8067. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  8068. 0, -1, 1, 1);
  8069. if (this.imageLayer) {
  8070. var position = this.getCanvasPosition(entry.x, entry.y);
  8071. this.imageLayer.appendImage({
  8072. imgData: imgData,
  8073. left: position[0],
  8074. top: position[1],
  8075. width: w,
  8076. height: h
  8077. });
  8078. }
  8079. ctx.restore();
  8080. }
  8081. },
  8082. paintSolidColorImageMask:
  8083. function CanvasGraphics_paintSolidColorImageMask() {
  8084. this.ctx.fillRect(0, 0, 1, 1);
  8085. },
  8086. paintXObject: function CanvasGraphics_paintXObject() {
  8087. warn('Unsupported \'paintXObject\' command.');
  8088. },
  8089. // Marked content
  8090. markPoint: function CanvasGraphics_markPoint(tag) {
  8091. // TODO Marked content.
  8092. },
  8093. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8094. // TODO Marked content.
  8095. },
  8096. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8097. // TODO Marked content.
  8098. },
  8099. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  8100. tag, properties) {
  8101. // TODO Marked content.
  8102. },
  8103. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8104. // TODO Marked content.
  8105. },
  8106. // Compatibility
  8107. beginCompat: function CanvasGraphics_beginCompat() {
  8108. // TODO ignore undefined operators (should we do that anyway?)
  8109. },
  8110. endCompat: function CanvasGraphics_endCompat() {
  8111. // TODO stop ignoring undefined operators
  8112. },
  8113. // Helper functions
  8114. consumePath: function CanvasGraphics_consumePath() {
  8115. var ctx = this.ctx;
  8116. if (this.pendingClip) {
  8117. if (this.pendingClip === EO_CLIP) {
  8118. if (ctx.mozFillRule !== undefined) {
  8119. ctx.mozFillRule = 'evenodd';
  8120. ctx.clip();
  8121. ctx.mozFillRule = 'nonzero';
  8122. } else {
  8123. ctx.clip('evenodd');
  8124. }
  8125. } else {
  8126. ctx.clip();
  8127. }
  8128. this.pendingClip = null;
  8129. }
  8130. ctx.beginPath();
  8131. },
  8132. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8133. if (this.cachedGetSinglePixelWidth === null) {
  8134. // NOTE: The `save` and `restore` commands used below is a workaround
  8135. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8136. // from intermittently returning incorrect values in Firefox, see:
  8137. // https://github.com/mozilla/pdf.js/issues/7188.
  8138. this.ctx.save();
  8139. var inverse = this.ctx.mozCurrentTransformInverse;
  8140. this.ctx.restore();
  8141. // max of the current horizontal and vertical scale
  8142. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  8143. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  8144. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  8145. }
  8146. return this.cachedGetSinglePixelWidth;
  8147. },
  8148. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8149. var transform = this.ctx.mozCurrentTransform;
  8150. return [
  8151. transform[0] * x + transform[2] * y + transform[4],
  8152. transform[1] * x + transform[3] * y + transform[5]
  8153. ];
  8154. }
  8155. };
  8156. for (var op in OPS) {
  8157. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8158. }
  8159. return CanvasGraphics;
  8160. })();
  8161. exports.CanvasGraphics = CanvasGraphics;
  8162. exports.createScratchCanvas = createScratchCanvas;
  8163. }));
  8164. (function (root, factory) {
  8165. {
  8166. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  8167. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  8168. root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8169. }
  8170. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  8171. displayMetadata, displayDOMUtils, amdRequire) {
  8172. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8173. var MessageHandler = sharedUtil.MessageHandler;
  8174. var MissingPDFException = sharedUtil.MissingPDFException;
  8175. var PageViewport = sharedUtil.PageViewport;
  8176. var PasswordResponses = sharedUtil.PasswordResponses;
  8177. var PasswordException = sharedUtil.PasswordException;
  8178. var StatTimer = sharedUtil.StatTimer;
  8179. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8180. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8181. var Util = sharedUtil.Util;
  8182. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8183. var error = sharedUtil.error;
  8184. var deprecated = sharedUtil.deprecated;
  8185. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8186. var info = sharedUtil.info;
  8187. var isInt = sharedUtil.isInt;
  8188. var isArray = sharedUtil.isArray;
  8189. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8190. var isSameOrigin = sharedUtil.isSameOrigin;
  8191. var loadJpegStream = sharedUtil.loadJpegStream;
  8192. var stringToBytes = sharedUtil.stringToBytes;
  8193. var globalScope = sharedUtil.globalScope;
  8194. var warn = sharedUtil.warn;
  8195. var FontFaceObject = displayFontLoader.FontFaceObject;
  8196. var FontLoader = displayFontLoader.FontLoader;
  8197. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8198. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8199. var Metadata = displayMetadata.Metadata;
  8200. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8201. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  8202. var isWorkerDisabled = false;
  8203. var workerSrc;
  8204. var isPostMessageTransfersDisabled = false;
  8205. var useRequireEnsure = false;
  8206. if (typeof window === 'undefined') {
  8207. // node.js - disable worker and set require.ensure.
  8208. isWorkerDisabled = true;
  8209. if (typeof require.ensure === 'undefined') {
  8210. require.ensure = require('node-ensure');
  8211. }
  8212. useRequireEnsure = true;
  8213. }
  8214. if (typeof __webpack_require__ !== 'undefined') {
  8215. useRequireEnsure = true;
  8216. }
  8217. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8218. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8219. }
  8220. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8221. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  8222. require.ensure([], function () {
  8223. var worker = require('./pdf.worker.js');
  8224. callback(worker.WorkerMessageHandler);
  8225. });
  8226. }) : dynamicLoaderSupported ? (function (callback) {
  8227. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8228. callback(worker.WorkerMessageHandler);
  8229. });
  8230. }) : null;
  8231. /**
  8232. * Document initialization / loading parameters object.
  8233. *
  8234. * @typedef {Object} DocumentInitParameters
  8235. * @property {string} url - The URL of the PDF.
  8236. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8237. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8238. * use atob() to convert it to a binary string first.
  8239. * @property {Object} httpHeaders - Basic authentication headers.
  8240. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8241. * Access-Control requests should be made using credentials such as cookies
  8242. * or authorization headers. The default is false.
  8243. * @property {string} password - For decrypting password-protected PDFs.
  8244. * @property {TypedArray} initialData - A typed array with the first portion or
  8245. * all of the pdf data. Used by the extension since some data is already
  8246. * loaded before the switch to range requests.
  8247. * @property {number} length - The PDF file length. It's used for progress
  8248. * reports and range requests operations.
  8249. * @property {PDFDataRangeTransport} range
  8250. * @property {number} rangeChunkSize - Optional parameter to specify
  8251. * maximum number of bytes fetched per range request. The default value is
  8252. * 2^16 = 65536.
  8253. * @property {PDFWorker} worker - The worker that will be used for the loading
  8254. * and parsing of the PDF data.
  8255. */
  8256. /**
  8257. * @typedef {Object} PDFDocumentStats
  8258. * @property {Array} streamTypes - Used stream types in the document (an item
  8259. * is set to true if specific stream ID was used in the document).
  8260. * @property {Array} fontTypes - Used font type in the document (an item is set
  8261. * to true if specific font ID was used in the document).
  8262. */
  8263. /**
  8264. * This is the main entry point for loading a PDF and interacting with it.
  8265. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8266. * is used, which means it must follow the same origin rules that any XHR does
  8267. * e.g. No cross domain requests without CORS.
  8268. *
  8269. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8270. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8271. * already populated with data or parameter object.
  8272. *
  8273. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8274. * if you want to manually serve range requests for data in the PDF.
  8275. *
  8276. * @param {function} passwordCallback (deprecated) It is used to request a
  8277. * password if wrong or no password was provided. The callback receives two
  8278. * parameters: function that needs to be called with new password and reason
  8279. * (see {PasswordResponses}).
  8280. *
  8281. * @param {function} progressCallback (deprecated) It is used to be able to
  8282. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8283. * a loading bar). The callback receives an {Object} with the properties:
  8284. * {number} loaded and {number} total.
  8285. *
  8286. * @return {PDFDocumentLoadingTask}
  8287. */
  8288. function getDocument(src, pdfDataRangeTransport,
  8289. passwordCallback, progressCallback) {
  8290. var task = new PDFDocumentLoadingTask();
  8291. // Support of the obsolete arguments (for compatibility with API v1.0)
  8292. if (arguments.length > 1) {
  8293. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  8294. 'passwordCallback or progressCallback argument');
  8295. }
  8296. if (pdfDataRangeTransport) {
  8297. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8298. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8299. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8300. pdfDataRangeTransport.length = src.length;
  8301. pdfDataRangeTransport.initialData = src.initialData;
  8302. if (!pdfDataRangeTransport.abort) {
  8303. pdfDataRangeTransport.abort = function () {};
  8304. }
  8305. }
  8306. src = Object.create(src);
  8307. src.range = pdfDataRangeTransport;
  8308. }
  8309. task.onPassword = passwordCallback || null;
  8310. task.onProgress = progressCallback || null;
  8311. var source;
  8312. if (typeof src === 'string') {
  8313. source = { url: src };
  8314. } else if (isArrayBuffer(src)) {
  8315. source = { data: src };
  8316. } else if (src instanceof PDFDataRangeTransport) {
  8317. source = { range: src };
  8318. } else {
  8319. if (typeof src !== 'object') {
  8320. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  8321. 'string or a parameter object');
  8322. }
  8323. if (!src.url && !src.data && !src.range) {
  8324. error('Invalid parameter object: need either .data, .range or .url');
  8325. }
  8326. source = src;
  8327. }
  8328. var params = {};
  8329. var rangeTransport = null;
  8330. var worker = null;
  8331. for (var key in source) {
  8332. if (key === 'url' && typeof window !== 'undefined') {
  8333. // The full path is required in the 'url' field.
  8334. params[key] = new URL(source[key], window.location).href;
  8335. continue;
  8336. } else if (key === 'range') {
  8337. rangeTransport = source[key];
  8338. continue;
  8339. } else if (key === 'worker') {
  8340. worker = source[key];
  8341. continue;
  8342. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8343. // Converting string or array-like data to Uint8Array.
  8344. var pdfBytes = source[key];
  8345. if (typeof pdfBytes === 'string') {
  8346. params[key] = stringToBytes(pdfBytes);
  8347. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  8348. !isNaN(pdfBytes.length)) {
  8349. params[key] = new Uint8Array(pdfBytes);
  8350. } else if (isArrayBuffer(pdfBytes)) {
  8351. params[key] = new Uint8Array(pdfBytes);
  8352. } else {
  8353. error('Invalid PDF binary data: either typed array, string or ' +
  8354. 'array-like object is expected in the data property.');
  8355. }
  8356. continue;
  8357. }
  8358. params[key] = source[key];
  8359. }
  8360. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8361. if (!worker) {
  8362. // Worker was not provided -- creating and owning our own.
  8363. worker = new PDFWorker();
  8364. task._worker = worker;
  8365. }
  8366. var docId = task.docId;
  8367. worker.promise.then(function () {
  8368. if (task.destroyed) {
  8369. throw new Error('Loading aborted');
  8370. }
  8371. return _fetchDocument(worker, params, rangeTransport, docId).then(
  8372. function (workerId) {
  8373. if (task.destroyed) {
  8374. throw new Error('Loading aborted');
  8375. }
  8376. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8377. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8378. task._transport = transport;
  8379. messageHandler.send('Ready', null);
  8380. });
  8381. }).catch(task._capability.reject);
  8382. return task;
  8383. }
  8384. /**
  8385. * Starts fetching of specified PDF document/data.
  8386. * @param {PDFWorker} worker
  8387. * @param {Object} source
  8388. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8389. * @param {string} docId Unique document id, used as MessageHandler id.
  8390. * @returns {Promise} The promise, which is resolved when worker id of
  8391. * MessageHandler is known.
  8392. * @private
  8393. */
  8394. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8395. if (worker.destroyed) {
  8396. return Promise.reject(new Error('Worker was destroyed'));
  8397. }
  8398. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8399. source.disableStream = getDefaultSetting('disableStream');
  8400. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8401. if (pdfDataRangeTransport) {
  8402. source.length = pdfDataRangeTransport.length;
  8403. source.initialData = pdfDataRangeTransport.initialData;
  8404. }
  8405. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8406. docId: docId,
  8407. source: source,
  8408. disableRange: getDefaultSetting('disableRange'),
  8409. maxImageSize: getDefaultSetting('maxImageSize'),
  8410. cMapUrl: getDefaultSetting('cMapUrl'),
  8411. cMapPacked: getDefaultSetting('cMapPacked'),
  8412. disableFontFace: getDefaultSetting('disableFontFace'),
  8413. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8414. postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
  8415. !isPostMessageTransfersDisabled,
  8416. }).then(function (workerId) {
  8417. if (worker.destroyed) {
  8418. throw new Error('Worker was destroyed');
  8419. }
  8420. return workerId;
  8421. });
  8422. }
  8423. /**
  8424. * PDF document loading operation.
  8425. * @class
  8426. * @alias PDFDocumentLoadingTask
  8427. */
  8428. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  8429. var nextDocumentId = 0;
  8430. /** @constructs PDFDocumentLoadingTask */
  8431. function PDFDocumentLoadingTask() {
  8432. this._capability = createPromiseCapability();
  8433. this._transport = null;
  8434. this._worker = null;
  8435. /**
  8436. * Unique document loading task id -- used in MessageHandlers.
  8437. * @type {string}
  8438. */
  8439. this.docId = 'd' + (nextDocumentId++);
  8440. /**
  8441. * Shows if loading task is destroyed.
  8442. * @type {boolean}
  8443. */
  8444. this.destroyed = false;
  8445. /**
  8446. * Callback to request a password if wrong or no password was provided.
  8447. * The callback receives two parameters: function that needs to be called
  8448. * with new password and reason (see {PasswordResponses}).
  8449. */
  8450. this.onPassword = null;
  8451. /**
  8452. * Callback to be able to monitor the loading progress of the PDF file
  8453. * (necessary to implement e.g. a loading bar). The callback receives
  8454. * an {Object} with the properties: {number} loaded and {number} total.
  8455. */
  8456. this.onProgress = null;
  8457. /**
  8458. * Callback to when unsupported feature is used. The callback receives
  8459. * an {UNSUPPORTED_FEATURES} argument.
  8460. */
  8461. this.onUnsupportedFeature = null;
  8462. }
  8463. PDFDocumentLoadingTask.prototype =
  8464. /** @lends PDFDocumentLoadingTask.prototype */ {
  8465. /**
  8466. * @return {Promise}
  8467. */
  8468. get promise() {
  8469. return this._capability.promise;
  8470. },
  8471. /**
  8472. * Aborts all network requests and destroys worker.
  8473. * @return {Promise} A promise that is resolved after destruction activity
  8474. * is completed.
  8475. */
  8476. destroy: function () {
  8477. this.destroyed = true;
  8478. var transportDestroyed = !this._transport ? Promise.resolve() :
  8479. this._transport.destroy();
  8480. return transportDestroyed.then(function () {
  8481. this._transport = null;
  8482. if (this._worker) {
  8483. this._worker.destroy();
  8484. this._worker = null;
  8485. }
  8486. }.bind(this));
  8487. },
  8488. /**
  8489. * Registers callbacks to indicate the document loading completion.
  8490. *
  8491. * @param {function} onFulfilled The callback for the loading completion.
  8492. * @param {function} onRejected The callback for the loading failure.
  8493. * @return {Promise} A promise that is resolved after the onFulfilled or
  8494. * onRejected callback.
  8495. */
  8496. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8497. return this.promise.then.apply(this.promise, arguments);
  8498. }
  8499. };
  8500. return PDFDocumentLoadingTask;
  8501. })();
  8502. /**
  8503. * Abstract class to support range requests file loading.
  8504. * @class
  8505. * @alias PDFDataRangeTransport
  8506. * @param {number} length
  8507. * @param {Uint8Array} initialData
  8508. */
  8509. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8510. function PDFDataRangeTransport(length, initialData) {
  8511. this.length = length;
  8512. this.initialData = initialData;
  8513. this._rangeListeners = [];
  8514. this._progressListeners = [];
  8515. this._progressiveReadListeners = [];
  8516. this._readyCapability = createPromiseCapability();
  8517. }
  8518. PDFDataRangeTransport.prototype =
  8519. /** @lends PDFDataRangeTransport.prototype */ {
  8520. addRangeListener:
  8521. function PDFDataRangeTransport_addRangeListener(listener) {
  8522. this._rangeListeners.push(listener);
  8523. },
  8524. addProgressListener:
  8525. function PDFDataRangeTransport_addProgressListener(listener) {
  8526. this._progressListeners.push(listener);
  8527. },
  8528. addProgressiveReadListener:
  8529. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8530. this._progressiveReadListeners.push(listener);
  8531. },
  8532. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8533. var listeners = this._rangeListeners;
  8534. for (var i = 0, n = listeners.length; i < n; ++i) {
  8535. listeners[i](begin, chunk);
  8536. }
  8537. },
  8538. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8539. this._readyCapability.promise.then(function () {
  8540. var listeners = this._progressListeners;
  8541. for (var i = 0, n = listeners.length; i < n; ++i) {
  8542. listeners[i](loaded);
  8543. }
  8544. }.bind(this));
  8545. },
  8546. onDataProgressiveRead:
  8547. function PDFDataRangeTransport_onDataProgress(chunk) {
  8548. this._readyCapability.promise.then(function () {
  8549. var listeners = this._progressiveReadListeners;
  8550. for (var i = 0, n = listeners.length; i < n; ++i) {
  8551. listeners[i](chunk);
  8552. }
  8553. }.bind(this));
  8554. },
  8555. transportReady: function PDFDataRangeTransport_transportReady() {
  8556. this._readyCapability.resolve();
  8557. },
  8558. requestDataRange:
  8559. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8560. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8561. },
  8562. abort: function PDFDataRangeTransport_abort() {
  8563. }
  8564. };
  8565. return PDFDataRangeTransport;
  8566. })();
  8567. /**
  8568. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8569. * properties that can be read synchronously.
  8570. * @class
  8571. * @alias PDFDocumentProxy
  8572. */
  8573. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8574. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8575. this.pdfInfo = pdfInfo;
  8576. this.transport = transport;
  8577. this.loadingTask = loadingTask;
  8578. }
  8579. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8580. /**
  8581. * @return {number} Total number of pages the PDF contains.
  8582. */
  8583. get numPages() {
  8584. return this.pdfInfo.numPages;
  8585. },
  8586. /**
  8587. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8588. * unique.
  8589. */
  8590. get fingerprint() {
  8591. return this.pdfInfo.fingerprint;
  8592. },
  8593. /**
  8594. * @param {number} pageNumber The page number to get. The first page is 1.
  8595. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8596. * object.
  8597. */
  8598. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8599. return this.transport.getPage(pageNumber);
  8600. },
  8601. /**
  8602. * @param {{num: number, gen: number}} ref The page reference. Must have
  8603. * the 'num' and 'gen' properties.
  8604. * @return {Promise} A promise that is resolved with the page index that is
  8605. * associated with the reference.
  8606. */
  8607. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8608. return this.transport.getPageIndex(ref);
  8609. },
  8610. /**
  8611. * @return {Promise} A promise that is resolved with a lookup table for
  8612. * mapping named destinations to reference numbers.
  8613. *
  8614. * This can be slow for large documents: use getDestination instead
  8615. */
  8616. getDestinations: function PDFDocumentProxy_getDestinations() {
  8617. return this.transport.getDestinations();
  8618. },
  8619. /**
  8620. * @param {string} id The named destination to get.
  8621. * @return {Promise} A promise that is resolved with all information
  8622. * of the given named destination.
  8623. */
  8624. getDestination: function PDFDocumentProxy_getDestination(id) {
  8625. return this.transport.getDestination(id);
  8626. },
  8627. /**
  8628. * @return {Promise} A promise that is resolved with:
  8629. * an Array containing the pageLabels that correspond to the pageIndexes,
  8630. * or `null` when no pageLabels are present in the PDF file.
  8631. */
  8632. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8633. return this.transport.getPageLabels();
  8634. },
  8635. /**
  8636. * @return {Promise} A promise that is resolved with a lookup table for
  8637. * mapping named attachments to their content.
  8638. */
  8639. getAttachments: function PDFDocumentProxy_getAttachments() {
  8640. return this.transport.getAttachments();
  8641. },
  8642. /**
  8643. * @return {Promise} A promise that is resolved with an array of all the
  8644. * JavaScript strings in the name tree.
  8645. */
  8646. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8647. return this.transport.getJavaScript();
  8648. },
  8649. /**
  8650. * @return {Promise} A promise that is resolved with an {Array} that is a
  8651. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8652. * [
  8653. * {
  8654. * title: string,
  8655. * bold: boolean,
  8656. * italic: boolean,
  8657. * color: rgb Uint8Array,
  8658. * dest: dest obj,
  8659. * url: string,
  8660. * items: array of more items like this
  8661. * },
  8662. * ...
  8663. * ].
  8664. */
  8665. getOutline: function PDFDocumentProxy_getOutline() {
  8666. return this.transport.getOutline();
  8667. },
  8668. /**
  8669. * @return {Promise} A promise that is resolved with an {Object} that has
  8670. * info and metadata properties. Info is an {Object} filled with anything
  8671. * available in the information dictionary and similarly metadata is a
  8672. * {Metadata} object with information from the metadata section of the PDF.
  8673. */
  8674. getMetadata: function PDFDocumentProxy_getMetadata() {
  8675. return this.transport.getMetadata();
  8676. },
  8677. /**
  8678. * @return {Promise} A promise that is resolved with a TypedArray that has
  8679. * the raw data from the PDF.
  8680. */
  8681. getData: function PDFDocumentProxy_getData() {
  8682. return this.transport.getData();
  8683. },
  8684. /**
  8685. * @return {Promise} A promise that is resolved when the document's data
  8686. * is loaded. It is resolved with an {Object} that contains the length
  8687. * property that indicates size of the PDF data in bytes.
  8688. */
  8689. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8690. return this.transport.downloadInfoCapability.promise;
  8691. },
  8692. /**
  8693. * @return {Promise} A promise this is resolved with current stats about
  8694. * document structures (see {@link PDFDocumentStats}).
  8695. */
  8696. getStats: function PDFDocumentProxy_getStats() {
  8697. return this.transport.getStats();
  8698. },
  8699. /**
  8700. * Cleans up resources allocated by the document, e.g. created @font-face.
  8701. */
  8702. cleanup: function PDFDocumentProxy_cleanup() {
  8703. this.transport.startCleanup();
  8704. },
  8705. /**
  8706. * Destroys current document instance and terminates worker.
  8707. */
  8708. destroy: function PDFDocumentProxy_destroy() {
  8709. return this.loadingTask.destroy();
  8710. }
  8711. };
  8712. return PDFDocumentProxy;
  8713. })();
  8714. /**
  8715. * Page getTextContent parameters.
  8716. *
  8717. * @typedef {Object} getTextContentParameters
  8718. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8719. * whitespace with standard spaces (0x20). The default value is `false`.
  8720. * @param {boolean} disableCombineTextItems - do not attempt to combine
  8721. * same line {@link TextItem}'s. The default value is `false`.
  8722. */
  8723. /**
  8724. * Page text content.
  8725. *
  8726. * @typedef {Object} TextContent
  8727. * @property {array} items - array of {@link TextItem}
  8728. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8729. * name.
  8730. */
  8731. /**
  8732. * Page text content part.
  8733. *
  8734. * @typedef {Object} TextItem
  8735. * @property {string} str - text content.
  8736. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8737. * @property {array} transform - transformation matrix.
  8738. * @property {number} width - width in device space.
  8739. * @property {number} height - height in device space.
  8740. * @property {string} fontName - font name used by pdf.js for converted font.
  8741. */
  8742. /**
  8743. * Text style.
  8744. *
  8745. * @typedef {Object} TextStyle
  8746. * @property {number} ascent - font ascent.
  8747. * @property {number} descent - font descent.
  8748. * @property {boolean} vertical - text is in vertical mode.
  8749. * @property {string} fontFamily - possible font family
  8750. */
  8751. /**
  8752. * Page annotation parameters.
  8753. *
  8754. * @typedef {Object} GetAnnotationsParameters
  8755. * @param {string} intent - Determines the annotations that will be fetched,
  8756. * can be either 'display' (viewable annotations) or 'print'
  8757. * (printable annotations).
  8758. * If the parameter is omitted, all annotations are fetched.
  8759. */
  8760. /**
  8761. * Page render parameters.
  8762. *
  8763. * @typedef {Object} RenderParameters
  8764. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8765. * @property {PageViewport} viewport - Rendering viewport obtained by
  8766. * calling of PDFPage.getViewport method.
  8767. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8768. * (default value is 'display').
  8769. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  8770. * interactive form elements are rendered in the display
  8771. * layer. If so, we do not render them on canvas as well.
  8772. * @property {Array} transform - (optional) Additional transform, applied
  8773. * just before viewport transform.
  8774. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8775. * endLayout and appendImage functions.
  8776. * @property {function} continueCallback - (deprecated) A function that will be
  8777. * called each time the rendering is paused. To continue
  8778. * rendering call the function that is the first argument
  8779. * to the callback.
  8780. */
  8781. /**
  8782. * PDF page operator list.
  8783. *
  8784. * @typedef {Object} PDFOperatorList
  8785. * @property {Array} fnArray - Array containing the operator functions.
  8786. * @property {Array} argsArray - Array containing the arguments of the
  8787. * functions.
  8788. */
  8789. /**
  8790. * Proxy to a PDFPage in the worker thread.
  8791. * @class
  8792. * @alias PDFPageProxy
  8793. */
  8794. var PDFPageProxy = (function PDFPageProxyClosure() {
  8795. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8796. this.pageIndex = pageIndex;
  8797. this.pageInfo = pageInfo;
  8798. this.transport = transport;
  8799. this.stats = new StatTimer();
  8800. this.stats.enabled = getDefaultSetting('enableStats');
  8801. this.commonObjs = transport.commonObjs;
  8802. this.objs = new PDFObjects();
  8803. this.cleanupAfterRender = false;
  8804. this.pendingCleanup = false;
  8805. this.intentStates = Object.create(null);
  8806. this.destroyed = false;
  8807. }
  8808. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8809. /**
  8810. * @return {number} Page number of the page. First page is 1.
  8811. */
  8812. get pageNumber() {
  8813. return this.pageIndex + 1;
  8814. },
  8815. /**
  8816. * @return {number} The number of degrees the page is rotated clockwise.
  8817. */
  8818. get rotate() {
  8819. return this.pageInfo.rotate;
  8820. },
  8821. /**
  8822. * @return {Object} The reference that points to this page. It has 'num' and
  8823. * 'gen' properties.
  8824. */
  8825. get ref() {
  8826. return this.pageInfo.ref;
  8827. },
  8828. /**
  8829. * @return {Array} An array of the visible portion of the PDF page in the
  8830. * user space units - [x1, y1, x2, y2].
  8831. */
  8832. get view() {
  8833. return this.pageInfo.view;
  8834. },
  8835. /**
  8836. * @param {number} scale The desired scale of the viewport.
  8837. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8838. * defaults to the page rotation.
  8839. * @return {PageViewport} Contains 'width' and 'height' properties
  8840. * along with transforms required for rendering.
  8841. */
  8842. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8843. if (arguments.length < 2) {
  8844. rotate = this.rotate;
  8845. }
  8846. return new PageViewport(this.view, scale, rotate, 0, 0);
  8847. },
  8848. /**
  8849. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8850. * @return {Promise} A promise that is resolved with an {Array} of the
  8851. * annotation objects.
  8852. */
  8853. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8854. var intent = (params && params.intent) || null;
  8855. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8856. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8857. intent);
  8858. this.annotationsIntent = intent;
  8859. }
  8860. return this.annotationsPromise;
  8861. },
  8862. /**
  8863. * Begins the process of rendering a page to the desired context.
  8864. * @param {RenderParameters} params Page render parameters.
  8865. * @return {RenderTask} An object that contains the promise, which
  8866. * is resolved when the page finishes rendering.
  8867. */
  8868. render: function PDFPageProxy_render(params) {
  8869. var stats = this.stats;
  8870. stats.time('Overall');
  8871. // If there was a pending destroy cancel it so no cleanup happens during
  8872. // this call to render.
  8873. this.pendingCleanup = false;
  8874. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8875. var renderInteractiveForms = (params.renderInteractiveForms === true ?
  8876. true : /* Default */ false);
  8877. if (!this.intentStates[renderingIntent]) {
  8878. this.intentStates[renderingIntent] = Object.create(null);
  8879. }
  8880. var intentState = this.intentStates[renderingIntent];
  8881. // If there's no displayReadyCapability yet, then the operatorList
  8882. // was never requested before. Make the request and create the promise.
  8883. if (!intentState.displayReadyCapability) {
  8884. intentState.receivingOperatorList = true;
  8885. intentState.displayReadyCapability = createPromiseCapability();
  8886. intentState.operatorList = {
  8887. fnArray: [],
  8888. argsArray: [],
  8889. lastChunk: false
  8890. };
  8891. this.stats.time('Page Request');
  8892. this.transport.messageHandler.send('RenderPageRequest', {
  8893. pageIndex: this.pageNumber - 1,
  8894. intent: renderingIntent,
  8895. renderInteractiveForms: renderInteractiveForms,
  8896. });
  8897. }
  8898. var internalRenderTask = new InternalRenderTask(complete, params,
  8899. this.objs,
  8900. this.commonObjs,
  8901. intentState.operatorList,
  8902. this.pageNumber);
  8903. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8904. if (!intentState.renderTasks) {
  8905. intentState.renderTasks = [];
  8906. }
  8907. intentState.renderTasks.push(internalRenderTask);
  8908. var renderTask = internalRenderTask.task;
  8909. // Obsolete parameter support
  8910. if (params.continueCallback) {
  8911. deprecated('render is used with continueCallback parameter');
  8912. renderTask.onContinue = params.continueCallback;
  8913. }
  8914. var self = this;
  8915. intentState.displayReadyCapability.promise.then(
  8916. function pageDisplayReadyPromise(transparency) {
  8917. if (self.pendingCleanup) {
  8918. complete();
  8919. return;
  8920. }
  8921. stats.time('Rendering');
  8922. internalRenderTask.initializeGraphics(transparency);
  8923. internalRenderTask.operatorListChanged();
  8924. },
  8925. function pageDisplayReadPromiseError(reason) {
  8926. complete(reason);
  8927. }
  8928. );
  8929. function complete(error) {
  8930. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8931. if (i >= 0) {
  8932. intentState.renderTasks.splice(i, 1);
  8933. }
  8934. if (self.cleanupAfterRender) {
  8935. self.pendingCleanup = true;
  8936. }
  8937. self._tryCleanup();
  8938. if (error) {
  8939. internalRenderTask.capability.reject(error);
  8940. } else {
  8941. internalRenderTask.capability.resolve();
  8942. }
  8943. stats.timeEnd('Rendering');
  8944. stats.timeEnd('Overall');
  8945. }
  8946. return renderTask;
  8947. },
  8948. /**
  8949. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8950. * object that represents page's operator list.
  8951. */
  8952. getOperatorList: function PDFPageProxy_getOperatorList() {
  8953. function operatorListChanged() {
  8954. if (intentState.operatorList.lastChunk) {
  8955. intentState.opListReadCapability.resolve(intentState.operatorList);
  8956. var i = intentState.renderTasks.indexOf(opListTask);
  8957. if (i >= 0) {
  8958. intentState.renderTasks.splice(i, 1);
  8959. }
  8960. }
  8961. }
  8962. var renderingIntent = 'oplist';
  8963. if (!this.intentStates[renderingIntent]) {
  8964. this.intentStates[renderingIntent] = Object.create(null);
  8965. }
  8966. var intentState = this.intentStates[renderingIntent];
  8967. var opListTask;
  8968. if (!intentState.opListReadCapability) {
  8969. opListTask = {};
  8970. opListTask.operatorListChanged = operatorListChanged;
  8971. intentState.receivingOperatorList = true;
  8972. intentState.opListReadCapability = createPromiseCapability();
  8973. intentState.renderTasks = [];
  8974. intentState.renderTasks.push(opListTask);
  8975. intentState.operatorList = {
  8976. fnArray: [],
  8977. argsArray: [],
  8978. lastChunk: false
  8979. };
  8980. this.transport.messageHandler.send('RenderPageRequest', {
  8981. pageIndex: this.pageIndex,
  8982. intent: renderingIntent
  8983. });
  8984. }
  8985. return intentState.opListReadCapability.promise;
  8986. },
  8987. /**
  8988. * @param {getTextContentParameters} params - getTextContent parameters.
  8989. * @return {Promise} That is resolved a {@link TextContent}
  8990. * object that represent the page text content.
  8991. */
  8992. getTextContent: function PDFPageProxy_getTextContent(params) {
  8993. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8994. pageIndex: this.pageNumber - 1,
  8995. normalizeWhitespace: (params && params.normalizeWhitespace === true ?
  8996. true : /* Default */ false),
  8997. combineTextItems: (params && params.disableCombineTextItems === true ?
  8998. false : /* Default */ true),
  8999. });
  9000. },
  9001. /**
  9002. * Destroys page object.
  9003. */
  9004. _destroy: function PDFPageProxy_destroy() {
  9005. this.destroyed = true;
  9006. this.transport.pageCache[this.pageIndex] = null;
  9007. var waitOn = [];
  9008. Object.keys(this.intentStates).forEach(function(intent) {
  9009. if (intent === 'oplist') {
  9010. // Avoid errors below, since the renderTasks are just stubs.
  9011. return;
  9012. }
  9013. var intentState = this.intentStates[intent];
  9014. intentState.renderTasks.forEach(function(renderTask) {
  9015. var renderCompleted = renderTask.capability.promise.
  9016. catch(function () {}); // ignoring failures
  9017. waitOn.push(renderCompleted);
  9018. renderTask.cancel();
  9019. });
  9020. }, this);
  9021. this.objs.clear();
  9022. this.annotationsPromise = null;
  9023. this.pendingCleanup = false;
  9024. return Promise.all(waitOn);
  9025. },
  9026. /**
  9027. * Cleans up resources allocated by the page. (deprecated)
  9028. */
  9029. destroy: function() {
  9030. deprecated('page destroy method, use cleanup() instead');
  9031. this.cleanup();
  9032. },
  9033. /**
  9034. * Cleans up resources allocated by the page.
  9035. */
  9036. cleanup: function PDFPageProxy_cleanup() {
  9037. this.pendingCleanup = true;
  9038. this._tryCleanup();
  9039. },
  9040. /**
  9041. * For internal use only. Attempts to clean up if rendering is in a state
  9042. * where that's possible.
  9043. * @ignore
  9044. */
  9045. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9046. if (!this.pendingCleanup ||
  9047. Object.keys(this.intentStates).some(function(intent) {
  9048. var intentState = this.intentStates[intent];
  9049. return (intentState.renderTasks.length !== 0 ||
  9050. intentState.receivingOperatorList);
  9051. }, this)) {
  9052. return;
  9053. }
  9054. Object.keys(this.intentStates).forEach(function(intent) {
  9055. delete this.intentStates[intent];
  9056. }, this);
  9057. this.objs.clear();
  9058. this.annotationsPromise = null;
  9059. this.pendingCleanup = false;
  9060. },
  9061. /**
  9062. * For internal use only.
  9063. * @ignore
  9064. */
  9065. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  9066. intent) {
  9067. var intentState = this.intentStates[intent];
  9068. // TODO Refactor RenderPageRequest to separate rendering
  9069. // and operator list logic
  9070. if (intentState.displayReadyCapability) {
  9071. intentState.displayReadyCapability.resolve(transparency);
  9072. }
  9073. },
  9074. /**
  9075. * For internal use only.
  9076. * @ignore
  9077. */
  9078. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  9079. intent) {
  9080. var intentState = this.intentStates[intent];
  9081. var i, ii;
  9082. // Add the new chunk to the current operator list.
  9083. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9084. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9085. intentState.operatorList.argsArray.push(
  9086. operatorListChunk.argsArray[i]);
  9087. }
  9088. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9089. // Notify all the rendering tasks there are more operators to be consumed.
  9090. for (i = 0; i < intentState.renderTasks.length; i++) {
  9091. intentState.renderTasks[i].operatorListChanged();
  9092. }
  9093. if (operatorListChunk.lastChunk) {
  9094. intentState.receivingOperatorList = false;
  9095. this._tryCleanup();
  9096. }
  9097. }
  9098. };
  9099. return PDFPageProxy;
  9100. })();
  9101. /**
  9102. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9103. * WorkerTransport for them. If creation of a web worker is not possible,
  9104. * a "fake" worker will be used instead.
  9105. * @class
  9106. */
  9107. var PDFWorker = (function PDFWorkerClosure() {
  9108. var nextFakeWorkerId = 0;
  9109. function getWorkerSrc() {
  9110. if (typeof workerSrc !== 'undefined') {
  9111. return workerSrc;
  9112. }
  9113. if (getDefaultSetting('workerSrc')) {
  9114. return getDefaultSetting('workerSrc');
  9115. }
  9116. if (pdfjsFilePath) {
  9117. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9118. }
  9119. error('No PDFJS.workerSrc specified');
  9120. }
  9121. var fakeWorkerFilesLoadedCapability;
  9122. // Loads worker code into main thread.
  9123. function setupFakeWorkerGlobal() {
  9124. var WorkerMessageHandler;
  9125. if (!fakeWorkerFilesLoadedCapability) {
  9126. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9127. // In the developer build load worker_loader which in turn loads all the
  9128. // other files and resolves the promise. In production only the
  9129. // pdf.worker.js file is needed.
  9130. var loader = fakeWorkerFilesLoader || function (callback) {
  9131. Util.loadScript(getWorkerSrc(), function () {
  9132. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9133. });
  9134. };
  9135. loader(fakeWorkerFilesLoadedCapability.resolve);
  9136. }
  9137. return fakeWorkerFilesLoadedCapability.promise;
  9138. }
  9139. function FakeWorkerPort(defer) {
  9140. this._listeners = [];
  9141. this._defer = defer;
  9142. this._deferred = Promise.resolve(undefined);
  9143. }
  9144. FakeWorkerPort.prototype = {
  9145. postMessage: function (obj, transfers) {
  9146. function cloneValue(value) {
  9147. // Trying to perform a structured clone close to the spec, including
  9148. // transfers.
  9149. if (typeof value !== 'object' || value === null) {
  9150. return value;
  9151. }
  9152. if (cloned.has(value)) { // already cloned the object
  9153. return cloned.get(value);
  9154. }
  9155. var result;
  9156. var buffer;
  9157. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9158. // We found object with ArrayBuffer (typed array).
  9159. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9160. if (value === buffer) {
  9161. // Special case when we are faking typed arrays in compatibility.js.
  9162. result = value;
  9163. } else if (transferable) {
  9164. result = new value.constructor(buffer, value.byteOffset,
  9165. value.byteLength);
  9166. } else {
  9167. result = new value.constructor(value);
  9168. }
  9169. cloned.set(value, result);
  9170. return result;
  9171. }
  9172. result = isArray(value) ? [] : {};
  9173. cloned.set(value, result); // adding to cache now for cyclic references
  9174. // Cloning all value and object properties, however ignoring properties
  9175. // defined via getter.
  9176. for (var i in value) {
  9177. var desc, p = value;
  9178. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9179. p = Object.getPrototypeOf(p);
  9180. }
  9181. if (typeof desc.value === 'undefined' ||
  9182. typeof desc.value === 'function') {
  9183. continue;
  9184. }
  9185. result[i] = cloneValue(desc.value);
  9186. }
  9187. return result;
  9188. }
  9189. if (!this._defer) {
  9190. this._listeners.forEach(function (listener) {
  9191. listener.call(this, {data: obj});
  9192. }, this);
  9193. return;
  9194. }
  9195. var cloned = new WeakMap();
  9196. var e = {data: cloneValue(obj)};
  9197. this._deferred.then(function () {
  9198. this._listeners.forEach(function (listener) {
  9199. listener.call(this, e);
  9200. }, this);
  9201. }.bind(this));
  9202. },
  9203. addEventListener: function (name, listener) {
  9204. this._listeners.push(listener);
  9205. },
  9206. removeEventListener: function (name, listener) {
  9207. var i = this._listeners.indexOf(listener);
  9208. this._listeners.splice(i, 1);
  9209. },
  9210. terminate: function () {
  9211. this._listeners = [];
  9212. }
  9213. };
  9214. function createCDNWrapper(url) {
  9215. // We will rely on blob URL's property to specify origin.
  9216. // We want this function to fail in case if createObjectURL or Blob do not
  9217. // exist or fail for some reason -- our Worker creation will fail anyway.
  9218. var wrapper = 'importScripts(\'' + url + '\');';
  9219. return URL.createObjectURL(new Blob([wrapper]));
  9220. }
  9221. function PDFWorker(name) {
  9222. this.name = name;
  9223. this.destroyed = false;
  9224. this._readyCapability = createPromiseCapability();
  9225. this._port = null;
  9226. this._webWorker = null;
  9227. this._messageHandler = null;
  9228. this._initialize();
  9229. }
  9230. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  9231. get promise() {
  9232. return this._readyCapability.promise;
  9233. },
  9234. get port() {
  9235. return this._port;
  9236. },
  9237. get messageHandler() {
  9238. return this._messageHandler;
  9239. },
  9240. _initialize: function PDFWorker_initialize() {
  9241. // If worker support isn't disabled explicit and the browser has worker
  9242. // support, create a new web worker and test if it/the browser fulfills
  9243. // all requirements to run parts of pdf.js in a web worker.
  9244. // Right now, the requirement is, that an Uint8Array is still an
  9245. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9246. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') &&
  9247. typeof Worker !== 'undefined') {
  9248. var workerSrc = getWorkerSrc();
  9249. try {
  9250. // Wraps workerSrc path into blob URL, if the former does not belong
  9251. // to the same origin.
  9252. if (!isSameOrigin(window.location.href, workerSrc)) {
  9253. workerSrc = createCDNWrapper(
  9254. new URL(workerSrc, window.location).href);
  9255. }
  9256. // Some versions of FF can't create a worker on localhost, see:
  9257. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9258. var worker = new Worker(workerSrc);
  9259. var messageHandler = new MessageHandler('main', 'worker', worker);
  9260. var terminateEarly = function() {
  9261. worker.removeEventListener('error', onWorkerError);
  9262. messageHandler.destroy();
  9263. worker.terminate();
  9264. if (this.destroyed) {
  9265. this._readyCapability.reject(new Error('Worker was destroyed'));
  9266. } else {
  9267. // Fall back to fake worker if the termination is caused by an
  9268. // error (e.g. NetworkError / SecurityError).
  9269. this._setupFakeWorker();
  9270. }
  9271. }.bind(this);
  9272. var onWorkerError = function(event) {
  9273. if (!this._webWorker) {
  9274. // Worker failed to initialize due to an error. Clean up and fall
  9275. // back to the fake worker.
  9276. terminateEarly();
  9277. }
  9278. }.bind(this);
  9279. worker.addEventListener('error', onWorkerError);
  9280. messageHandler.on('test', function PDFWorker_test(data) {
  9281. worker.removeEventListener('error', onWorkerError);
  9282. if (this.destroyed) {
  9283. terminateEarly();
  9284. return; // worker was destroyed
  9285. }
  9286. var supportTypedArray = data && data.supportTypedArray;
  9287. if (supportTypedArray) {
  9288. this._messageHandler = messageHandler;
  9289. this._port = worker;
  9290. this._webWorker = worker;
  9291. if (!data.supportTransfers) {
  9292. isPostMessageTransfersDisabled = true;
  9293. }
  9294. this._readyCapability.resolve();
  9295. // Send global setting, e.g. verbosity level.
  9296. messageHandler.send('configure', {
  9297. verbosity: getVerbosityLevel()
  9298. });
  9299. } else {
  9300. this._setupFakeWorker();
  9301. messageHandler.destroy();
  9302. worker.terminate();
  9303. }
  9304. }.bind(this));
  9305. messageHandler.on('console_log', function (data) {
  9306. console.log.apply(console, data);
  9307. });
  9308. messageHandler.on('console_error', function (data) {
  9309. console.error.apply(console, data);
  9310. });
  9311. messageHandler.on('ready', function (data) {
  9312. worker.removeEventListener('error', onWorkerError);
  9313. if (this.destroyed) {
  9314. terminateEarly();
  9315. return; // worker was destroyed
  9316. }
  9317. try {
  9318. sendTest();
  9319. } catch (e) {
  9320. // We need fallback to a faked worker.
  9321. this._setupFakeWorker();
  9322. }
  9323. }.bind(this));
  9324. var sendTest = function () {
  9325. var postMessageTransfers =
  9326. getDefaultSetting('postMessageTransfers') &&
  9327. !isPostMessageTransfersDisabled;
  9328. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9329. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9330. // typed array. Also, checking if we can use transfers.
  9331. try {
  9332. messageHandler.send('test', testObj, [testObj.buffer]);
  9333. } catch (ex) {
  9334. info('Cannot use postMessage transfers');
  9335. testObj[0] = 0;
  9336. messageHandler.send('test', testObj);
  9337. }
  9338. };
  9339. // It might take time for worker to initialize (especially when AMD
  9340. // loader is used). We will try to send test immediately, and then
  9341. // when 'ready' message will arrive. The worker shall process only
  9342. // first received 'test'.
  9343. sendTest();
  9344. return;
  9345. } catch (e) {
  9346. info('The worker has been disabled.');
  9347. }
  9348. }
  9349. // Either workers are disabled, not supported or have thrown an exception.
  9350. // Thus, we fallback to a faked worker.
  9351. this._setupFakeWorker();
  9352. },
  9353. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9354. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9355. warn('Setting up fake worker.');
  9356. isWorkerDisabled = true;
  9357. }
  9358. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9359. if (this.destroyed) {
  9360. this._readyCapability.reject(new Error('Worker was destroyed'));
  9361. return;
  9362. }
  9363. // We cannot turn on proper fake port simulation (this includes
  9364. // structured cloning) when typed arrays are not supported. Relying
  9365. // on a chance that messages will be sent in proper order.
  9366. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9367. var port = new FakeWorkerPort(isTypedArraysPresent);
  9368. this._port = port;
  9369. // All fake workers use the same port, making id unique.
  9370. var id = 'fake' + (nextFakeWorkerId++);
  9371. // If the main thread is our worker, setup the handling for the
  9372. // messages -- the main thread sends to it self.
  9373. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9374. WorkerMessageHandler.setup(workerHandler, port);
  9375. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9376. this._messageHandler = messageHandler;
  9377. this._readyCapability.resolve();
  9378. }.bind(this));
  9379. },
  9380. /**
  9381. * Destroys the worker instance.
  9382. */
  9383. destroy: function PDFWorker_destroy() {
  9384. this.destroyed = true;
  9385. if (this._webWorker) {
  9386. // We need to terminate only web worker created resource.
  9387. this._webWorker.terminate();
  9388. this._webWorker = null;
  9389. }
  9390. this._port = null;
  9391. if (this._messageHandler) {
  9392. this._messageHandler.destroy();
  9393. this._messageHandler = null;
  9394. }
  9395. }
  9396. };
  9397. return PDFWorker;
  9398. })();
  9399. /**
  9400. * For internal use only.
  9401. * @ignore
  9402. */
  9403. var WorkerTransport = (function WorkerTransportClosure() {
  9404. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9405. this.messageHandler = messageHandler;
  9406. this.loadingTask = loadingTask;
  9407. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9408. this.commonObjs = new PDFObjects();
  9409. this.fontLoader = new FontLoader(loadingTask.docId);
  9410. this.destroyed = false;
  9411. this.destroyCapability = null;
  9412. this.pageCache = [];
  9413. this.pagePromises = [];
  9414. this.downloadInfoCapability = createPromiseCapability();
  9415. this.setupMessageHandler();
  9416. }
  9417. WorkerTransport.prototype = {
  9418. destroy: function WorkerTransport_destroy() {
  9419. if (this.destroyCapability) {
  9420. return this.destroyCapability.promise;
  9421. }
  9422. this.destroyed = true;
  9423. this.destroyCapability = createPromiseCapability();
  9424. var waitOn = [];
  9425. // We need to wait for all renderings to be completed, e.g.
  9426. // timeout/rAF can take a long time.
  9427. this.pageCache.forEach(function (page) {
  9428. if (page) {
  9429. waitOn.push(page._destroy());
  9430. }
  9431. });
  9432. this.pageCache = [];
  9433. this.pagePromises = [];
  9434. var self = this;
  9435. // We also need to wait for the worker to finish its long running tasks.
  9436. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9437. waitOn.push(terminated);
  9438. Promise.all(waitOn).then(function () {
  9439. self.fontLoader.clear();
  9440. if (self.pdfDataRangeTransport) {
  9441. self.pdfDataRangeTransport.abort();
  9442. self.pdfDataRangeTransport = null;
  9443. }
  9444. if (self.messageHandler) {
  9445. self.messageHandler.destroy();
  9446. self.messageHandler = null;
  9447. }
  9448. self.destroyCapability.resolve();
  9449. }, this.destroyCapability.reject);
  9450. return this.destroyCapability.promise;
  9451. },
  9452. setupMessageHandler:
  9453. function WorkerTransport_setupMessageHandler() {
  9454. var messageHandler = this.messageHandler;
  9455. function updatePassword(password) {
  9456. messageHandler.send('UpdatePassword', password);
  9457. }
  9458. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9459. if (pdfDataRangeTransport) {
  9460. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  9461. messageHandler.send('OnDataRange', {
  9462. begin: begin,
  9463. chunk: chunk
  9464. });
  9465. });
  9466. pdfDataRangeTransport.addProgressListener(function(loaded) {
  9467. messageHandler.send('OnDataProgress', {
  9468. loaded: loaded
  9469. });
  9470. });
  9471. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  9472. messageHandler.send('OnDataRange', {
  9473. chunk: chunk
  9474. });
  9475. });
  9476. messageHandler.on('RequestDataRange',
  9477. function transportDataRange(data) {
  9478. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9479. }, this);
  9480. }
  9481. messageHandler.on('GetDoc', function transportDoc(data) {
  9482. var pdfInfo = data.pdfInfo;
  9483. this.numPages = data.pdfInfo.numPages;
  9484. var loadingTask = this.loadingTask;
  9485. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9486. this.pdfDocument = pdfDocument;
  9487. loadingTask._capability.resolve(pdfDocument);
  9488. }, this);
  9489. messageHandler.on('NeedPassword',
  9490. function transportNeedPassword(exception) {
  9491. var loadingTask = this.loadingTask;
  9492. if (loadingTask.onPassword) {
  9493. return loadingTask.onPassword(updatePassword,
  9494. PasswordResponses.NEED_PASSWORD);
  9495. }
  9496. loadingTask._capability.reject(
  9497. new PasswordException(exception.message, exception.code));
  9498. }, this);
  9499. messageHandler.on('IncorrectPassword',
  9500. function transportIncorrectPassword(exception) {
  9501. var loadingTask = this.loadingTask;
  9502. if (loadingTask.onPassword) {
  9503. return loadingTask.onPassword(updatePassword,
  9504. PasswordResponses.INCORRECT_PASSWORD);
  9505. }
  9506. loadingTask._capability.reject(
  9507. new PasswordException(exception.message, exception.code));
  9508. }, this);
  9509. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9510. this.loadingTask._capability.reject(
  9511. new InvalidPDFException(exception.message));
  9512. }, this);
  9513. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9514. this.loadingTask._capability.reject(
  9515. new MissingPDFException(exception.message));
  9516. }, this);
  9517. messageHandler.on('UnexpectedResponse',
  9518. function transportUnexpectedResponse(exception) {
  9519. this.loadingTask._capability.reject(
  9520. new UnexpectedResponseException(exception.message, exception.status));
  9521. }, this);
  9522. messageHandler.on('UnknownError',
  9523. function transportUnknownError(exception) {
  9524. this.loadingTask._capability.reject(
  9525. new UnknownErrorException(exception.message, exception.details));
  9526. }, this);
  9527. messageHandler.on('DataLoaded', function transportPage(data) {
  9528. this.downloadInfoCapability.resolve(data);
  9529. }, this);
  9530. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9531. if (this.pdfDataRangeTransport) {
  9532. this.pdfDataRangeTransport.transportReady();
  9533. }
  9534. }, this);
  9535. messageHandler.on('StartRenderPage', function transportRender(data) {
  9536. if (this.destroyed) {
  9537. return; // Ignore any pending requests if the worker was terminated.
  9538. }
  9539. var page = this.pageCache[data.pageIndex];
  9540. page.stats.timeEnd('Page Request');
  9541. page._startRenderPage(data.transparency, data.intent);
  9542. }, this);
  9543. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9544. if (this.destroyed) {
  9545. return; // Ignore any pending requests if the worker was terminated.
  9546. }
  9547. var page = this.pageCache[data.pageIndex];
  9548. page._renderPageChunk(data.operatorList, data.intent);
  9549. }, this);
  9550. messageHandler.on('commonobj', function transportObj(data) {
  9551. if (this.destroyed) {
  9552. return; // Ignore any pending requests if the worker was terminated.
  9553. }
  9554. var id = data[0];
  9555. var type = data[1];
  9556. if (this.commonObjs.hasData(id)) {
  9557. return;
  9558. }
  9559. switch (type) {
  9560. case 'Font':
  9561. var exportedData = data[2];
  9562. if ('error' in exportedData) {
  9563. var exportedError = exportedData.error;
  9564. warn('Error during font loading: ' + exportedError);
  9565. this.commonObjs.resolve(id, exportedError);
  9566. break;
  9567. }
  9568. var fontRegistry = null;
  9569. if (getDefaultSetting('pdfBug') && globalScope.FontInspector &&
  9570. globalScope['FontInspector'].enabled) {
  9571. fontRegistry = {
  9572. registerFont: function (font, url) {
  9573. globalScope['FontInspector'].fontAdded(font, url);
  9574. }
  9575. };
  9576. }
  9577. var font = new FontFaceObject(exportedData, {
  9578. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9579. disableFontFace: getDefaultSetting('disableFontFace'),
  9580. fontRegistry: fontRegistry
  9581. });
  9582. this.fontLoader.bind(
  9583. [font],
  9584. function fontReady(fontObjs) {
  9585. this.commonObjs.resolve(id, font);
  9586. }.bind(this)
  9587. );
  9588. break;
  9589. case 'FontPath':
  9590. this.commonObjs.resolve(id, data[2]);
  9591. break;
  9592. default:
  9593. error('Got unknown common object type ' + type);
  9594. }
  9595. }, this);
  9596. messageHandler.on('obj', function transportObj(data) {
  9597. if (this.destroyed) {
  9598. return; // Ignore any pending requests if the worker was terminated.
  9599. }
  9600. var id = data[0];
  9601. var pageIndex = data[1];
  9602. var type = data[2];
  9603. var pageProxy = this.pageCache[pageIndex];
  9604. var imageData;
  9605. if (pageProxy.objs.hasData(id)) {
  9606. return;
  9607. }
  9608. switch (type) {
  9609. case 'JpegStream':
  9610. imageData = data[3];
  9611. loadJpegStream(id, imageData, pageProxy.objs);
  9612. break;
  9613. case 'Image':
  9614. imageData = data[3];
  9615. pageProxy.objs.resolve(id, imageData);
  9616. // heuristics that will allow not to store large data
  9617. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9618. if (imageData && 'data' in imageData &&
  9619. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9620. pageProxy.cleanupAfterRender = true;
  9621. }
  9622. break;
  9623. default:
  9624. error('Got unknown object type ' + type);
  9625. }
  9626. }, this);
  9627. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9628. if (this.destroyed) {
  9629. return; // Ignore any pending requests if the worker was terminated.
  9630. }
  9631. var loadingTask = this.loadingTask;
  9632. if (loadingTask.onProgress) {
  9633. loadingTask.onProgress({
  9634. loaded: data.loaded,
  9635. total: data.total
  9636. });
  9637. }
  9638. }, this);
  9639. messageHandler.on('PageError', function transportError(data) {
  9640. if (this.destroyed) {
  9641. return; // Ignore any pending requests if the worker was terminated.
  9642. }
  9643. var page = this.pageCache[data.pageNum - 1];
  9644. var intentState = page.intentStates[data.intent];
  9645. if (intentState.displayReadyCapability) {
  9646. intentState.displayReadyCapability.reject(data.error);
  9647. } else {
  9648. error(data.error);
  9649. }
  9650. if (intentState.operatorList) {
  9651. // Mark operator list as complete.
  9652. intentState.operatorList.lastChunk = true;
  9653. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9654. intentState.renderTasks[i].operatorListChanged();
  9655. }
  9656. }
  9657. }, this);
  9658. messageHandler.on('UnsupportedFeature',
  9659. function transportUnsupportedFeature(data) {
  9660. if (this.destroyed) {
  9661. return; // Ignore any pending requests if the worker was terminated.
  9662. }
  9663. var featureId = data.featureId;
  9664. var loadingTask = this.loadingTask;
  9665. if (loadingTask.onUnsupportedFeature) {
  9666. loadingTask.onUnsupportedFeature(featureId);
  9667. }
  9668. _UnsupportedManager.notify(featureId);
  9669. }, this);
  9670. messageHandler.on('JpegDecode', function(data) {
  9671. if (this.destroyed) {
  9672. return Promise.reject(new Error('Worker was destroyed'));
  9673. }
  9674. var imageUrl = data[0];
  9675. var components = data[1];
  9676. if (components !== 3 && components !== 1) {
  9677. return Promise.reject(
  9678. new Error('Only 3 components or 1 component can be returned'));
  9679. }
  9680. return new Promise(function (resolve, reject) {
  9681. var img = new Image();
  9682. img.onload = function () {
  9683. var width = img.width;
  9684. var height = img.height;
  9685. var size = width * height;
  9686. var rgbaLength = size * 4;
  9687. var buf = new Uint8Array(size * components);
  9688. var tmpCanvas = createScratchCanvas(width, height);
  9689. var tmpCtx = tmpCanvas.getContext('2d');
  9690. tmpCtx.drawImage(img, 0, 0);
  9691. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9692. var i, j;
  9693. if (components === 3) {
  9694. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9695. buf[j] = data[i];
  9696. buf[j + 1] = data[i + 1];
  9697. buf[j + 2] = data[i + 2];
  9698. }
  9699. } else if (components === 1) {
  9700. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9701. buf[j] = data[i];
  9702. }
  9703. }
  9704. resolve({ data: buf, width: width, height: height});
  9705. };
  9706. img.onerror = function () {
  9707. reject(new Error('JpegDecode failed to load image'));
  9708. };
  9709. img.src = imageUrl;
  9710. });
  9711. }, this);
  9712. },
  9713. getData: function WorkerTransport_getData() {
  9714. return this.messageHandler.sendWithPromise('GetData', null);
  9715. },
  9716. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9717. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9718. return Promise.reject(new Error('Invalid page request'));
  9719. }
  9720. var pageIndex = pageNumber - 1;
  9721. if (pageIndex in this.pagePromises) {
  9722. return this.pagePromises[pageIndex];
  9723. }
  9724. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9725. pageIndex: pageIndex
  9726. }).then(function (pageInfo) {
  9727. if (this.destroyed) {
  9728. throw new Error('Transport destroyed');
  9729. }
  9730. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9731. this.pageCache[pageIndex] = page;
  9732. return page;
  9733. }.bind(this));
  9734. this.pagePromises[pageIndex] = promise;
  9735. return promise;
  9736. },
  9737. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9738. return this.messageHandler.sendWithPromise('GetPageIndex', {
  9739. ref: ref,
  9740. }).catch(function (reason) {
  9741. return Promise.reject(new Error(reason));
  9742. });
  9743. },
  9744. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9745. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9746. pageIndex: pageIndex,
  9747. intent: intent,
  9748. });
  9749. },
  9750. getDestinations: function WorkerTransport_getDestinations() {
  9751. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9752. },
  9753. getDestination: function WorkerTransport_getDestination(id) {
  9754. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9755. },
  9756. getPageLabels: function WorkerTransport_getPageLabels() {
  9757. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9758. },
  9759. getAttachments: function WorkerTransport_getAttachments() {
  9760. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9761. },
  9762. getJavaScript: function WorkerTransport_getJavaScript() {
  9763. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9764. },
  9765. getOutline: function WorkerTransport_getOutline() {
  9766. return this.messageHandler.sendWithPromise('GetOutline', null);
  9767. },
  9768. getMetadata: function WorkerTransport_getMetadata() {
  9769. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9770. then(function transportMetadata(results) {
  9771. return {
  9772. info: results[0],
  9773. metadata: (results[1] ? new Metadata(results[1]) : null)
  9774. };
  9775. });
  9776. },
  9777. getStats: function WorkerTransport_getStats() {
  9778. return this.messageHandler.sendWithPromise('GetStats', null);
  9779. },
  9780. startCleanup: function WorkerTransport_startCleanup() {
  9781. this.messageHandler.sendWithPromise('Cleanup', null).
  9782. then(function endCleanup() {
  9783. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9784. var page = this.pageCache[i];
  9785. if (page) {
  9786. page.cleanup();
  9787. }
  9788. }
  9789. this.commonObjs.clear();
  9790. this.fontLoader.clear();
  9791. }.bind(this));
  9792. }
  9793. };
  9794. return WorkerTransport;
  9795. })();
  9796. /**
  9797. * A PDF document and page is built of many objects. E.g. there are objects
  9798. * for fonts, images, rendering code and such. These objects might get processed
  9799. * inside of a worker. The `PDFObjects` implements some basic functions to
  9800. * manage these objects.
  9801. * @ignore
  9802. */
  9803. var PDFObjects = (function PDFObjectsClosure() {
  9804. function PDFObjects() {
  9805. this.objs = Object.create(null);
  9806. }
  9807. PDFObjects.prototype = {
  9808. /**
  9809. * Internal function.
  9810. * Ensures there is an object defined for `objId`.
  9811. */
  9812. ensureObj: function PDFObjects_ensureObj(objId) {
  9813. if (this.objs[objId]) {
  9814. return this.objs[objId];
  9815. }
  9816. var obj = {
  9817. capability: createPromiseCapability(),
  9818. data: null,
  9819. resolved: false
  9820. };
  9821. this.objs[objId] = obj;
  9822. return obj;
  9823. },
  9824. /**
  9825. * If called *without* callback, this returns the data of `objId` but the
  9826. * object needs to be resolved. If it isn't, this function throws.
  9827. *
  9828. * If called *with* a callback, the callback is called with the data of the
  9829. * object once the object is resolved. That means, if you call this
  9830. * function and the object is already resolved, the callback gets called
  9831. * right away.
  9832. */
  9833. get: function PDFObjects_get(objId, callback) {
  9834. // If there is a callback, then the get can be async and the object is
  9835. // not required to be resolved right now
  9836. if (callback) {
  9837. this.ensureObj(objId).capability.promise.then(callback);
  9838. return null;
  9839. }
  9840. // If there isn't a callback, the user expects to get the resolved data
  9841. // directly.
  9842. var obj = this.objs[objId];
  9843. // If there isn't an object yet or the object isn't resolved, then the
  9844. // data isn't ready yet!
  9845. if (!obj || !obj.resolved) {
  9846. error('Requesting object that isn\'t resolved yet ' + objId);
  9847. }
  9848. return obj.data;
  9849. },
  9850. /**
  9851. * Resolves the object `objId` with optional `data`.
  9852. */
  9853. resolve: function PDFObjects_resolve(objId, data) {
  9854. var obj = this.ensureObj(objId);
  9855. obj.resolved = true;
  9856. obj.data = data;
  9857. obj.capability.resolve(data);
  9858. },
  9859. isResolved: function PDFObjects_isResolved(objId) {
  9860. var objs = this.objs;
  9861. if (!objs[objId]) {
  9862. return false;
  9863. } else {
  9864. return objs[objId].resolved;
  9865. }
  9866. },
  9867. hasData: function PDFObjects_hasData(objId) {
  9868. return this.isResolved(objId);
  9869. },
  9870. /**
  9871. * Returns the data of `objId` if object exists, null otherwise.
  9872. */
  9873. getData: function PDFObjects_getData(objId) {
  9874. var objs = this.objs;
  9875. if (!objs[objId] || !objs[objId].resolved) {
  9876. return null;
  9877. } else {
  9878. return objs[objId].data;
  9879. }
  9880. },
  9881. clear: function PDFObjects_clear() {
  9882. this.objs = Object.create(null);
  9883. }
  9884. };
  9885. return PDFObjects;
  9886. })();
  9887. /**
  9888. * Allows controlling of the rendering tasks.
  9889. * @class
  9890. * @alias RenderTask
  9891. */
  9892. var RenderTask = (function RenderTaskClosure() {
  9893. function RenderTask(internalRenderTask) {
  9894. this._internalRenderTask = internalRenderTask;
  9895. /**
  9896. * Callback for incremental rendering -- a function that will be called
  9897. * each time the rendering is paused. To continue rendering call the
  9898. * function that is the first argument to the callback.
  9899. * @type {function}
  9900. */
  9901. this.onContinue = null;
  9902. }
  9903. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9904. /**
  9905. * Promise for rendering task completion.
  9906. * @return {Promise}
  9907. */
  9908. get promise() {
  9909. return this._internalRenderTask.capability.promise;
  9910. },
  9911. /**
  9912. * Cancels the rendering task. If the task is currently rendering it will
  9913. * not be cancelled until graphics pauses with a timeout. The promise that
  9914. * this object extends will resolved when cancelled.
  9915. */
  9916. cancel: function RenderTask_cancel() {
  9917. this._internalRenderTask.cancel();
  9918. },
  9919. /**
  9920. * Registers callbacks to indicate the rendering task completion.
  9921. *
  9922. * @param {function} onFulfilled The callback for the rendering completion.
  9923. * @param {function} onRejected The callback for the rendering failure.
  9924. * @return {Promise} A promise that is resolved after the onFulfilled or
  9925. * onRejected callback.
  9926. */
  9927. then: function RenderTask_then(onFulfilled, onRejected) {
  9928. return this.promise.then.apply(this.promise, arguments);
  9929. }
  9930. };
  9931. return RenderTask;
  9932. })();
  9933. /**
  9934. * For internal use only.
  9935. * @ignore
  9936. */
  9937. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9938. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9939. pageNumber) {
  9940. this.callback = callback;
  9941. this.params = params;
  9942. this.objs = objs;
  9943. this.commonObjs = commonObjs;
  9944. this.operatorListIdx = null;
  9945. this.operatorList = operatorList;
  9946. this.pageNumber = pageNumber;
  9947. this.running = false;
  9948. this.graphicsReadyCallback = null;
  9949. this.graphicsReady = false;
  9950. this.useRequestAnimationFrame = false;
  9951. this.cancelled = false;
  9952. this.capability = createPromiseCapability();
  9953. this.task = new RenderTask(this);
  9954. // caching this-bound methods
  9955. this._continueBound = this._continue.bind(this);
  9956. this._scheduleNextBound = this._scheduleNext.bind(this);
  9957. this._nextBound = this._next.bind(this);
  9958. }
  9959. InternalRenderTask.prototype = {
  9960. initializeGraphics:
  9961. function InternalRenderTask_initializeGraphics(transparency) {
  9962. if (this.cancelled) {
  9963. return;
  9964. }
  9965. if (getDefaultSetting('pdfBug') && globalScope.StepperManager &&
  9966. globalScope.StepperManager.enabled) {
  9967. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9968. this.stepper.init(this.operatorList);
  9969. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9970. }
  9971. var params = this.params;
  9972. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9973. this.objs, params.imageLayer);
  9974. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9975. this.operatorListIdx = 0;
  9976. this.graphicsReady = true;
  9977. if (this.graphicsReadyCallback) {
  9978. this.graphicsReadyCallback();
  9979. }
  9980. },
  9981. cancel: function InternalRenderTask_cancel() {
  9982. this.running = false;
  9983. this.cancelled = true;
  9984. this.callback('cancelled');
  9985. },
  9986. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9987. if (!this.graphicsReady) {
  9988. if (!this.graphicsReadyCallback) {
  9989. this.graphicsReadyCallback = this._continueBound;
  9990. }
  9991. return;
  9992. }
  9993. if (this.stepper) {
  9994. this.stepper.updateOperatorList(this.operatorList);
  9995. }
  9996. if (this.running) {
  9997. return;
  9998. }
  9999. this._continue();
  10000. },
  10001. _continue: function InternalRenderTask__continue() {
  10002. this.running = true;
  10003. if (this.cancelled) {
  10004. return;
  10005. }
  10006. if (this.task.onContinue) {
  10007. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10008. } else {
  10009. this._scheduleNext();
  10010. }
  10011. },
  10012. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10013. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10014. window.requestAnimationFrame(this._nextBound);
  10015. } else {
  10016. Promise.resolve(undefined).then(this._nextBound);
  10017. }
  10018. },
  10019. _next: function InternalRenderTask__next() {
  10020. if (this.cancelled) {
  10021. return;
  10022. }
  10023. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  10024. this.operatorListIdx,
  10025. this._continueBound,
  10026. this.stepper);
  10027. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10028. this.running = false;
  10029. if (this.operatorList.lastChunk) {
  10030. this.gfx.endDrawing();
  10031. this.callback();
  10032. }
  10033. }
  10034. }
  10035. };
  10036. return InternalRenderTask;
  10037. })();
  10038. /**
  10039. * (Deprecated) Global observer of unsupported feature usages. Use
  10040. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10041. */
  10042. var _UnsupportedManager = (function UnsupportedManagerClosure() {
  10043. var listeners = [];
  10044. return {
  10045. listen: function (cb) {
  10046. deprecated('Global UnsupportedManager.listen is used: ' +
  10047. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10048. listeners.push(cb);
  10049. },
  10050. notify: function (featureId) {
  10051. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10052. listeners[i](featureId);
  10053. }
  10054. }
  10055. };
  10056. })();
  10057. if (typeof pdfjsVersion !== 'undefined') {
  10058. exports.version = pdfjsVersion;
  10059. }
  10060. if (typeof pdfjsBuild !== 'undefined') {
  10061. exports.build = pdfjsBuild;
  10062. }
  10063. exports.getDocument = getDocument;
  10064. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10065. exports.PDFWorker = PDFWorker;
  10066. exports.PDFDocumentProxy = PDFDocumentProxy;
  10067. exports.PDFPageProxy = PDFPageProxy;
  10068. exports._UnsupportedManager = _UnsupportedManager;
  10069. }));
  10070. (function (root, factory) {
  10071. {
  10072. factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil,
  10073. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI,
  10074. root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer,
  10075. root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10076. }
  10077. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI,
  10078. displayAnnotationLayer, displayTextLayer, displayMetadata,
  10079. displaySVG) {
  10080. var globalScope = sharedUtil.globalScope;
  10081. var deprecated = sharedUtil.deprecated;
  10082. var warn = sharedUtil.warn;
  10083. var LinkTarget = displayDOMUtils.LinkTarget;
  10084. var isWorker = (typeof window === 'undefined');
  10085. // The global PDFJS object is now deprecated and will not be supported in
  10086. // the future. The members below are maintained for backward compatibility
  10087. // and shall not be extended or modified. If the global.js is included as
  10088. // a module, we will create a global PDFJS object instance or use existing.
  10089. if (!globalScope.PDFJS) {
  10090. globalScope.PDFJS = {};
  10091. }
  10092. var PDFJS = globalScope.PDFJS;
  10093. if (typeof pdfjsVersion !== 'undefined') {
  10094. PDFJS.version = pdfjsVersion;
  10095. }
  10096. if (typeof pdfjsBuild !== 'undefined') {
  10097. PDFJS.build = pdfjsBuild;
  10098. }
  10099. PDFJS.pdfBug = false;
  10100. if (PDFJS.verbosity !== undefined) {
  10101. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10102. }
  10103. delete PDFJS.verbosity;
  10104. Object.defineProperty(PDFJS, 'verbosity', {
  10105. get: function () { return sharedUtil.getVerbosityLevel(); },
  10106. set: function (level) { sharedUtil.setVerbosityLevel(level); },
  10107. enumerable: true,
  10108. configurable: true
  10109. });
  10110. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10111. PDFJS.OPS = sharedUtil.OPS;
  10112. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10113. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10114. PDFJS.shadow = sharedUtil.shadow;
  10115. PDFJS.createBlob = sharedUtil.createBlob;
  10116. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10117. return sharedUtil.createObjectURL(data, contentType,
  10118. PDFJS.disableCreateObjectURL);
  10119. };
  10120. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10121. configurable: true,
  10122. get: function PDFJS_isLittleEndian() {
  10123. var value = sharedUtil.isLittleEndian();
  10124. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10125. }
  10126. });
  10127. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10128. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10129. PDFJS.PasswordException = sharedUtil.PasswordException;
  10130. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10131. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10132. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10133. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10134. PDFJS.Util = sharedUtil.Util;
  10135. PDFJS.PageViewport = sharedUtil.PageViewport;
  10136. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10137. /**
  10138. * The maximum allowed image size in total pixels e.g. width * height. Images
  10139. * above this value will not be drawn. Use -1 for no limit.
  10140. * @var {number}
  10141. */
  10142. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  10143. -1 : PDFJS.maxImageSize);
  10144. /**
  10145. * The url of where the predefined Adobe CMaps are located. Include trailing
  10146. * slash.
  10147. * @var {string}
  10148. */
  10149. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  10150. /**
  10151. * Specifies if CMaps are binary packed.
  10152. * @var {boolean}
  10153. */
  10154. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10155. /**
  10156. * By default fonts are converted to OpenType fonts and loaded via font face
  10157. * rules. If disabled, the font will be rendered using a built in font
  10158. * renderer that constructs the glyphs with primitive path commands.
  10159. * @var {boolean}
  10160. */
  10161. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  10162. false : PDFJS.disableFontFace);
  10163. /**
  10164. * Path for image resources, mainly for annotation icons. Include trailing
  10165. * slash.
  10166. * @var {string}
  10167. */
  10168. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  10169. '' : PDFJS.imageResourcesPath);
  10170. /**
  10171. * Disable the web worker and run all code on the main thread. This will
  10172. * happen automatically if the browser doesn't support workers or sending
  10173. * typed arrays to workers.
  10174. * @var {boolean}
  10175. */
  10176. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  10177. false : PDFJS.disableWorker);
  10178. /**
  10179. * Path and filename of the worker file. Required when the worker is enabled
  10180. * in development mode. If unspecified in the production build, the worker
  10181. * will be loaded based on the location of the pdf.js file. It is recommended
  10182. * that the workerSrc is set in a custom application to prevent issues caused
  10183. * by third-party frameworks and libraries.
  10184. * @var {string}
  10185. */
  10186. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  10187. /**
  10188. * Disable range request loading of PDF files. When enabled and if the server
  10189. * supports partial content requests then the PDF will be fetched in chunks.
  10190. * Enabled (false) by default.
  10191. * @var {boolean}
  10192. */
  10193. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  10194. false : PDFJS.disableRange);
  10195. /**
  10196. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10197. * in chunks. This default behavior can be disabled.
  10198. * @var {boolean}
  10199. */
  10200. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  10201. false : PDFJS.disableStream);
  10202. /**
  10203. * Disable pre-fetching of PDF file data. When range requests are enabled
  10204. * PDF.js will automatically keep fetching more data even if it isn't needed
  10205. * to display the current page. This default behavior can be disabled.
  10206. *
  10207. * NOTE: It is also necessary to disable streaming, see above,
  10208. * in order for disabling of pre-fetching to work correctly.
  10209. * @var {boolean}
  10210. */
  10211. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  10212. false : PDFJS.disableAutoFetch);
  10213. /**
  10214. * Enables special hooks for debugging PDF.js.
  10215. * @var {boolean}
  10216. */
  10217. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  10218. /**
  10219. * Enables transfer usage in postMessage for ArrayBuffers.
  10220. * @var {boolean}
  10221. */
  10222. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  10223. true : PDFJS.postMessageTransfers);
  10224. /**
  10225. * Disables URL.createObjectURL usage.
  10226. * @var {boolean}
  10227. */
  10228. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  10229. false : PDFJS.disableCreateObjectURL);
  10230. /**
  10231. * Disables WebGL usage.
  10232. * @var {boolean}
  10233. */
  10234. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  10235. true : PDFJS.disableWebGL);
  10236. /**
  10237. * Specifies the |target| attribute for external links.
  10238. * The constants from PDFJS.LinkTarget should be used:
  10239. * - NONE [default]
  10240. * - SELF
  10241. * - BLANK
  10242. * - PARENT
  10243. * - TOP
  10244. * @var {number}
  10245. */
  10246. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  10247. LinkTarget.NONE : PDFJS.externalLinkTarget);
  10248. /**
  10249. * Specifies the |rel| attribute for external links. Defaults to stripping
  10250. * the referrer.
  10251. * @var {string}
  10252. */
  10253. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  10254. 'noreferrer' : PDFJS.externalLinkRel);
  10255. /**
  10256. * Determines if we can eval strings as JS. Primarily used to improve
  10257. * performance for font rendering.
  10258. * @var {boolean}
  10259. */
  10260. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  10261. true : PDFJS.isEvalSupported);
  10262. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10263. delete PDFJS.openExternalLinksInNewWindow;
  10264. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10265. get: function () {
  10266. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10267. },
  10268. set: function (value) {
  10269. if (value) {
  10270. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  10271. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10272. }
  10273. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10274. warn('PDFJS.externalLinkTarget is already initialized');
  10275. return;
  10276. }
  10277. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10278. },
  10279. enumerable: true,
  10280. configurable: true
  10281. });
  10282. if (savedOpenExternalLinksInNewWindow) {
  10283. /**
  10284. * (Deprecated) Opens external links in a new window if enabled.
  10285. * The default behavior opens external links in the PDF.js window.
  10286. *
  10287. * NOTE: This property has been deprecated, please use
  10288. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10289. * @var {boolean}
  10290. */
  10291. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10292. }
  10293. PDFJS.getDocument = displayAPI.getDocument;
  10294. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10295. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10296. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10297. configurable: true,
  10298. get: function PDFJS_hasCanvasTypedArrays() {
  10299. var value = displayDOMUtils.hasCanvasTypedArrays();
  10300. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10301. }
  10302. });
  10303. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10304. PDFJS.LinkTarget = LinkTarget;
  10305. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10306. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10307. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10308. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10309. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10310. PDFJS.Metadata = displayMetadata.Metadata;
  10311. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10312. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10313. exports.globalScope = globalScope;
  10314. exports.isWorker = isWorker;
  10315. exports.PDFJS = globalScope.PDFJS;
  10316. }));
  10317. }).call(pdfjsLibs);
  10318. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10319. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10320. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10321. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10322. exports.PDFDataRangeTransport =
  10323. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10324. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10325. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10326. exports.AnnotationLayer =
  10327. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10328. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10329. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10330. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10331. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10332. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10333. exports.UnexpectedResponseException =
  10334. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10335. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10336. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10337. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10338. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10339. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10340. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10341. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10342. exports.getFilenameFromUrl =
  10343. pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10344. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10345. }));