pdf.js 280 KB

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