pdf.js 327 KB

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