pdf.js 328 KB

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