pdf.js 305 KB

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