2
0

pdf_viewer.js 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211
  1. /* Copyright 2014 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /* jshint globalstrict: false */
  16. /* umdutils ignore */
  17. (function (root, factory) {
  18. 'use strict';
  19. if (typeof define === 'function' && define.amd) {
  20. define('pdfjs-dist/web/pdf_viewer', ['exports', 'pdfjs-dist/build/pdf'],
  21. factory);
  22. } else if (typeof exports !== 'undefined') {
  23. factory(exports, require('../build/pdf.js'));
  24. } else {
  25. factory((root.pdfjsDistWebPDFViewer = {}), root.pdfjsDistBuildPdf);
  26. }
  27. }(this, function (exports, pdfjsLib) {
  28. 'use strict';
  29. var pdfViewerLibs = {
  30. pdfjsWebPDFJS: pdfjsLib
  31. };
  32. (function () {
  33. (function (root, factory) {
  34. {
  35. factory((root.pdfjsWebPDFRenderingQueue = {}));
  36. }
  37. }(this, function (exports) {
  38. var CLEANUP_TIMEOUT = 30000;
  39. var RenderingStates = {
  40. INITIAL: 0,
  41. RUNNING: 1,
  42. PAUSED: 2,
  43. FINISHED: 3
  44. };
  45. /**
  46. * Controls rendering of the views for pages and thumbnails.
  47. * @class
  48. */
  49. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  50. /**
  51. * @constructs
  52. */
  53. function PDFRenderingQueue() {
  54. this.pdfViewer = null;
  55. this.pdfThumbnailViewer = null;
  56. this.onIdle = null;
  57. this.highestPriorityPage = null;
  58. this.idleTimeout = null;
  59. this.printing = false;
  60. this.isThumbnailViewEnabled = false;
  61. }
  62. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  63. /**
  64. * @param {PDFViewer} pdfViewer
  65. */
  66. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  67. this.pdfViewer = pdfViewer;
  68. },
  69. /**
  70. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  71. */
  72. setThumbnailViewer:
  73. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  74. this.pdfThumbnailViewer = pdfThumbnailViewer;
  75. },
  76. /**
  77. * @param {IRenderableView} view
  78. * @returns {boolean}
  79. */
  80. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  81. return this.highestPriorityPage === view.renderingId;
  82. },
  83. renderHighestPriority: function
  84. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  85. if (this.idleTimeout) {
  86. clearTimeout(this.idleTimeout);
  87. this.idleTimeout = null;
  88. }
  89. // Pages have a higher priority than thumbnails, so check them first.
  90. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  91. return;
  92. }
  93. // No pages needed rendering so check thumbnails.
  94. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  95. if (this.pdfThumbnailViewer.forceRendering()) {
  96. return;
  97. }
  98. }
  99. if (this.printing) {
  100. // If printing is currently ongoing do not reschedule cleanup.
  101. return;
  102. }
  103. if (this.onIdle) {
  104. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  105. }
  106. },
  107. getHighestPriority: function
  108. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  109. // The state has changed figure out which page has the highest priority to
  110. // render next (if any).
  111. // Priority:
  112. // 1 visible pages
  113. // 2 if last scrolled down page after the visible pages
  114. // 2 if last scrolled up page before the visible pages
  115. var visibleViews = visible.views;
  116. var numVisible = visibleViews.length;
  117. if (numVisible === 0) {
  118. return false;
  119. }
  120. for (var i = 0; i < numVisible; ++i) {
  121. var view = visibleViews[i].view;
  122. if (!this.isViewFinished(view)) {
  123. return view;
  124. }
  125. }
  126. // All the visible views have rendered, try to render next/previous pages.
  127. if (scrolledDown) {
  128. var nextPageIndex = visible.last.id;
  129. // ID's start at 1 so no need to add 1.
  130. if (views[nextPageIndex] &&
  131. !this.isViewFinished(views[nextPageIndex])) {
  132. return views[nextPageIndex];
  133. }
  134. } else {
  135. var previousPageIndex = visible.first.id - 2;
  136. if (views[previousPageIndex] &&
  137. !this.isViewFinished(views[previousPageIndex])) {
  138. return views[previousPageIndex];
  139. }
  140. }
  141. // Everything that needs to be rendered has been.
  142. return null;
  143. },
  144. /**
  145. * @param {IRenderableView} view
  146. * @returns {boolean}
  147. */
  148. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  149. return view.renderingState === RenderingStates.FINISHED;
  150. },
  151. /**
  152. * Render a page or thumbnail view. This calls the appropriate function
  153. * based on the views state. If the view is already rendered it will return
  154. * false.
  155. * @param {IRenderableView} view
  156. */
  157. renderView: function PDFRenderingQueue_renderView(view) {
  158. var state = view.renderingState;
  159. switch (state) {
  160. case RenderingStates.FINISHED:
  161. return false;
  162. case RenderingStates.PAUSED:
  163. this.highestPriorityPage = view.renderingId;
  164. view.resume();
  165. break;
  166. case RenderingStates.RUNNING:
  167. this.highestPriorityPage = view.renderingId;
  168. break;
  169. case RenderingStates.INITIAL:
  170. this.highestPriorityPage = view.renderingId;
  171. var continueRendering = function () {
  172. this.renderHighestPriority();
  173. }.bind(this);
  174. view.draw().then(continueRendering, continueRendering);
  175. break;
  176. }
  177. return true;
  178. },
  179. };
  180. return PDFRenderingQueue;
  181. })();
  182. exports.RenderingStates = RenderingStates;
  183. exports.PDFRenderingQueue = PDFRenderingQueue;
  184. }));
  185. (function (root, factory) {
  186. {
  187. factory((root.pdfjsWebDownloadManager = {}), root.pdfjsWebPDFJS);
  188. }
  189. }(this, function (exports, pdfjsLib) {
  190. function download(blobUrl, filename) {
  191. var a = document.createElement('a');
  192. if (a.click) {
  193. // Use a.click() if available. Otherwise, Chrome might show
  194. // "Unsafe JavaScript attempt to initiate a navigation change
  195. // for frame with URL" and not open the PDF at all.
  196. // Supported by (not mentioned = untested):
  197. // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
  198. // - Chrome 19 - 26 (18- does not support a.click)
  199. // - Opera 9 - 12.15
  200. // - Internet Explorer 6 - 10
  201. // - Safari 6 (5.1- does not support a.click)
  202. a.href = blobUrl;
  203. a.target = '_parent';
  204. // Use a.download if available. This increases the likelihood that
  205. // the file is downloaded instead of opened by another PDF plugin.
  206. if ('download' in a) {
  207. a.download = filename;
  208. }
  209. // <a> must be in the document for IE and recent Firefox versions.
  210. // (otherwise .click() is ignored)
  211. (document.body || document.documentElement).appendChild(a);
  212. a.click();
  213. a.parentNode.removeChild(a);
  214. } else {
  215. if (window.top === window &&
  216. blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  217. // If _parent == self, then opening an identical URL with different
  218. // location hash will only cause a navigation, not a download.
  219. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  220. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  221. }
  222. window.open(blobUrl, '_parent');
  223. }
  224. }
  225. function DownloadManager() {}
  226. DownloadManager.prototype = {
  227. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  228. if (!pdfjsLib.isValidUrl(url, true)) {
  229. return; // restricted/invalid URL
  230. }
  231. download(url + '#pdfjs.action=download', filename);
  232. },
  233. downloadData: function DownloadManager_downloadData(data, filename,
  234. contentType) {
  235. if (navigator.msSaveBlob) { // IE10 and above
  236. return navigator.msSaveBlob(new Blob([data], { type: contentType }),
  237. filename);
  238. }
  239. var blobUrl = pdfjsLib.createObjectURL(data, contentType,
  240. pdfjsLib.PDFJS.disableCreateObjectURL);
  241. download(blobUrl, filename);
  242. },
  243. download: function DownloadManager_download(blob, url, filename) {
  244. if (!URL) {
  245. // URL.createObjectURL is not supported
  246. this.downloadUrl(url, filename);
  247. return;
  248. }
  249. if (navigator.msSaveBlob) {
  250. // IE10 / IE11
  251. if (!navigator.msSaveBlob(blob, filename)) {
  252. this.downloadUrl(url, filename);
  253. }
  254. return;
  255. }
  256. var blobUrl = URL.createObjectURL(blob);
  257. download(blobUrl, filename);
  258. }
  259. };
  260. exports.DownloadManager = DownloadManager;
  261. }));
  262. (function (root, factory) {
  263. {
  264. factory((root.pdfjsWebUIUtils = {}), root.pdfjsWebPDFJS);
  265. }
  266. }(this, function (exports, pdfjsLib) {
  267. var CSS_UNITS = 96.0 / 72.0;
  268. var DEFAULT_SCALE_VALUE = 'auto';
  269. var DEFAULT_SCALE = 1.0;
  270. var UNKNOWN_SCALE = 0;
  271. var MAX_AUTO_SCALE = 1.25;
  272. var SCROLLBAR_PADDING = 40;
  273. var VERTICAL_PADDING = 5;
  274. var mozL10n = document.mozL10n || document.webL10n;
  275. var PDFJS = pdfjsLib.PDFJS;
  276. /**
  277. * Disables fullscreen support, and by extension Presentation Mode,
  278. * in browsers which support the fullscreen API.
  279. * @var {boolean}
  280. */
  281. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  282. false : PDFJS.disableFullscreen);
  283. /**
  284. * Enables CSS only zooming.
  285. * @var {boolean}
  286. */
  287. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  288. false : PDFJS.useOnlyCssZoom);
  289. /**
  290. * The maximum supported canvas size in total pixels e.g. width * height.
  291. * The default value is 4096 * 4096. Use -1 for no limit.
  292. * @var {number}
  293. */
  294. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  295. 16777216 : PDFJS.maxCanvasPixels);
  296. /**
  297. * Disables saving of the last position of the viewed PDF.
  298. * @var {boolean}
  299. */
  300. PDFJS.disableHistory = (PDFJS.disableHistory === undefined ?
  301. false : PDFJS.disableHistory);
  302. /**
  303. * Disables creation of the text layer that used for text selection and search.
  304. * @var {boolean}
  305. */
  306. PDFJS.disableTextLayer = (PDFJS.disableTextLayer === undefined ?
  307. false : PDFJS.disableTextLayer);
  308. /**
  309. * Disables maintaining the current position in the document when zooming.
  310. */
  311. PDFJS.ignoreCurrentPositionOnZoom = (PDFJS.ignoreCurrentPositionOnZoom ===
  312. undefined ? false : PDFJS.ignoreCurrentPositionOnZoom);
  313. /**
  314. * Interface locale settings.
  315. * @var {string}
  316. */
  317. PDFJS.locale = (PDFJS.locale === undefined ? navigator.language : PDFJS.locale);
  318. /**
  319. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  320. * @return {Object} The object with horizontal (sx) and vertical (sy)
  321. scales. The scaled property is set to false if scaling is
  322. not required, true otherwise.
  323. */
  324. function getOutputScale(ctx) {
  325. var devicePixelRatio = window.devicePixelRatio || 1;
  326. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  327. ctx.mozBackingStorePixelRatio ||
  328. ctx.msBackingStorePixelRatio ||
  329. ctx.oBackingStorePixelRatio ||
  330. ctx.backingStorePixelRatio || 1;
  331. var pixelRatio = devicePixelRatio / backingStoreRatio;
  332. return {
  333. sx: pixelRatio,
  334. sy: pixelRatio,
  335. scaled: pixelRatio !== 1
  336. };
  337. }
  338. /**
  339. * Scrolls specified element into view of its parent.
  340. * @param {Object} element - The element to be visible.
  341. * @param {Object} spot - An object with optional top and left properties,
  342. * specifying the offset from the top left edge.
  343. * @param {boolean} skipOverflowHiddenElements - Ignore elements that have
  344. * the CSS rule `overflow: hidden;` set. The default is false.
  345. */
  346. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  347. // Assuming offsetParent is available (it's not available when viewer is in
  348. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  349. // producing the error. See also animationStartedClosure.
  350. var parent = element.offsetParent;
  351. if (!parent) {
  352. console.error('offsetParent is not set -- cannot scroll');
  353. return;
  354. }
  355. var checkOverflow = skipOverflowHiddenElements || false;
  356. var offsetY = element.offsetTop + element.clientTop;
  357. var offsetX = element.offsetLeft + element.clientLeft;
  358. while (parent.clientHeight === parent.scrollHeight ||
  359. (checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
  360. if (parent.dataset._scaleY) {
  361. offsetY /= parent.dataset._scaleY;
  362. offsetX /= parent.dataset._scaleX;
  363. }
  364. offsetY += parent.offsetTop;
  365. offsetX += parent.offsetLeft;
  366. parent = parent.offsetParent;
  367. if (!parent) {
  368. return; // no need to scroll
  369. }
  370. }
  371. if (spot) {
  372. if (spot.top !== undefined) {
  373. offsetY += spot.top;
  374. }
  375. if (spot.left !== undefined) {
  376. offsetX += spot.left;
  377. parent.scrollLeft = offsetX;
  378. }
  379. }
  380. parent.scrollTop = offsetY;
  381. }
  382. /**
  383. * Helper function to start monitoring the scroll event and converting them into
  384. * PDF.js friendly one: with scroll debounce and scroll direction.
  385. */
  386. function watchScroll(viewAreaElement, callback) {
  387. var debounceScroll = function debounceScroll(evt) {
  388. if (rAF) {
  389. return;
  390. }
  391. // schedule an invocation of scroll for next animation frame.
  392. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  393. rAF = null;
  394. var currentY = viewAreaElement.scrollTop;
  395. var lastY = state.lastY;
  396. if (currentY !== lastY) {
  397. state.down = currentY > lastY;
  398. }
  399. state.lastY = currentY;
  400. callback(state);
  401. });
  402. };
  403. var state = {
  404. down: true,
  405. lastY: viewAreaElement.scrollTop,
  406. _eventHandler: debounceScroll
  407. };
  408. var rAF = null;
  409. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  410. return state;
  411. }
  412. /**
  413. * Helper function to parse query string (e.g. ?param1=value&parm2=...).
  414. */
  415. function parseQueryString(query) {
  416. var parts = query.split('&');
  417. var params = {};
  418. for (var i = 0, ii = parts.length; i < ii; ++i) {
  419. var param = parts[i].split('=');
  420. var key = param[0].toLowerCase();
  421. var value = param.length > 1 ? param[1] : null;
  422. params[decodeURIComponent(key)] = decodeURIComponent(value);
  423. }
  424. return params;
  425. }
  426. /**
  427. * Use binary search to find the index of the first item in a given array which
  428. * passes a given condition. The items are expected to be sorted in the sense
  429. * that if the condition is true for one item in the array, then it is also true
  430. * for all following items.
  431. *
  432. * @returns {Number} Index of the first array element to pass the test,
  433. * or |items.length| if no such element exists.
  434. */
  435. function binarySearchFirstItem(items, condition) {
  436. var minIndex = 0;
  437. var maxIndex = items.length - 1;
  438. if (items.length === 0 || !condition(items[maxIndex])) {
  439. return items.length;
  440. }
  441. if (condition(items[minIndex])) {
  442. return minIndex;
  443. }
  444. while (minIndex < maxIndex) {
  445. var currentIndex = (minIndex + maxIndex) >> 1;
  446. var currentItem = items[currentIndex];
  447. if (condition(currentItem)) {
  448. maxIndex = currentIndex;
  449. } else {
  450. minIndex = currentIndex + 1;
  451. }
  452. }
  453. return minIndex; /* === maxIndex */
  454. }
  455. /**
  456. * Approximates float number as a fraction using Farey sequence (max order
  457. * of 8).
  458. * @param {number} x - Positive float number.
  459. * @returns {Array} Estimated fraction: the first array item is a numerator,
  460. * the second one is a denominator.
  461. */
  462. function approximateFraction(x) {
  463. // Fast paths for int numbers or their inversions.
  464. if (Math.floor(x) === x) {
  465. return [x, 1];
  466. }
  467. var xinv = 1 / x;
  468. var limit = 8;
  469. if (xinv > limit) {
  470. return [1, limit];
  471. } else if (Math.floor(xinv) === xinv) {
  472. return [1, xinv];
  473. }
  474. var x_ = x > 1 ? xinv : x;
  475. // a/b and c/d are neighbours in Farey sequence.
  476. var a = 0, b = 1, c = 1, d = 1;
  477. // Limiting search to order 8.
  478. while (true) {
  479. // Generating next term in sequence (order of q).
  480. var p = a + c, q = b + d;
  481. if (q > limit) {
  482. break;
  483. }
  484. if (x_ <= p / q) {
  485. c = p; d = q;
  486. } else {
  487. a = p; b = q;
  488. }
  489. }
  490. // Select closest of the neighbours to x.
  491. if (x_ - a / b < c / d - x_) {
  492. return x_ === x ? [a, b] : [b, a];
  493. } else {
  494. return x_ === x ? [c, d] : [d, c];
  495. }
  496. }
  497. function roundToDivide(x, div) {
  498. var r = x % div;
  499. return r === 0 ? x : Math.round(x - r + div);
  500. }
  501. /**
  502. * Generic helper to find out what elements are visible within a scroll pane.
  503. */
  504. function getVisibleElements(scrollEl, views, sortByVisibility) {
  505. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  506. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  507. function isElementBottomBelowViewTop(view) {
  508. var element = view.div;
  509. var elementBottom =
  510. element.offsetTop + element.clientTop + element.clientHeight;
  511. return elementBottom > top;
  512. }
  513. var visible = [], view, element;
  514. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  515. var currentWidth, viewWidth;
  516. var firstVisibleElementInd = (views.length === 0) ? 0 :
  517. binarySearchFirstItem(views, isElementBottomBelowViewTop);
  518. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  519. view = views[i];
  520. element = view.div;
  521. currentHeight = element.offsetTop + element.clientTop;
  522. viewHeight = element.clientHeight;
  523. if (currentHeight > bottom) {
  524. break;
  525. }
  526. currentWidth = element.offsetLeft + element.clientLeft;
  527. viewWidth = element.clientWidth;
  528. if (currentWidth + viewWidth < left || currentWidth > right) {
  529. continue;
  530. }
  531. hiddenHeight = Math.max(0, top - currentHeight) +
  532. Math.max(0, currentHeight + viewHeight - bottom);
  533. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  534. visible.push({
  535. id: view.id,
  536. x: currentWidth,
  537. y: currentHeight,
  538. view: view,
  539. percent: percentHeight
  540. });
  541. }
  542. var first = visible[0];
  543. var last = visible[visible.length - 1];
  544. if (sortByVisibility) {
  545. visible.sort(function(a, b) {
  546. var pc = a.percent - b.percent;
  547. if (Math.abs(pc) > 0.001) {
  548. return -pc;
  549. }
  550. return a.id - b.id; // ensure stability
  551. });
  552. }
  553. return {first: first, last: last, views: visible};
  554. }
  555. /**
  556. * Event handler to suppress context menu.
  557. */
  558. function noContextMenuHandler(e) {
  559. e.preventDefault();
  560. }
  561. /**
  562. * Returns the filename or guessed filename from the url (see issue 3455).
  563. * url {String} The original PDF location.
  564. * @return {String} Guessed PDF file name.
  565. */
  566. function getPDFFileNameFromURL(url) {
  567. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  568. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  569. // Pattern to get last matching NAME.pdf
  570. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  571. var splitURI = reURI.exec(url);
  572. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  573. reFilename.exec(splitURI[2]) ||
  574. reFilename.exec(splitURI[3]);
  575. if (suggestedFilename) {
  576. suggestedFilename = suggestedFilename[0];
  577. if (suggestedFilename.indexOf('%') !== -1) {
  578. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  579. try {
  580. suggestedFilename =
  581. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  582. } catch(e) { // Possible (extremely rare) errors:
  583. // URIError "Malformed URI", e.g. for "%AA.pdf"
  584. // TypeError "null has no properties", e.g. for "%2F.pdf"
  585. }
  586. }
  587. }
  588. return suggestedFilename || 'document.pdf';
  589. }
  590. function normalizeWheelEventDelta(evt) {
  591. var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
  592. var angle = Math.atan2(evt.deltaY, evt.deltaX);
  593. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  594. // All that is left-up oriented has to change the sign.
  595. delta = -delta;
  596. }
  597. var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  598. var MOUSE_DOM_DELTA_LINE_MODE = 1;
  599. var MOUSE_PIXELS_PER_LINE = 30;
  600. var MOUSE_LINES_PER_PAGE = 30;
  601. // Converts delta to per-page units
  602. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  603. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  604. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  605. delta /= MOUSE_LINES_PER_PAGE;
  606. }
  607. return delta;
  608. }
  609. /**
  610. * Simple event bus for an application. Listeners are attached using the
  611. * `on` and `off` methods. To raise an event, the `dispatch` method shall be
  612. * used.
  613. */
  614. var EventBus = (function EventBusClosure() {
  615. function EventBus() {
  616. this._listeners = Object.create(null);
  617. }
  618. EventBus.prototype = {
  619. on: function EventBus_on(eventName, listener) {
  620. var eventListeners = this._listeners[eventName];
  621. if (!eventListeners) {
  622. eventListeners = [];
  623. this._listeners[eventName] = eventListeners;
  624. }
  625. eventListeners.push(listener);
  626. },
  627. off: function EventBus_on(eventName, listener) {
  628. var eventListeners = this._listeners[eventName];
  629. var i;
  630. if (!eventListeners || ((i = eventListeners.indexOf(listener)) < 0)) {
  631. return;
  632. }
  633. eventListeners.splice(i, 1);
  634. },
  635. dispatch: function EventBus_dispath(eventName) {
  636. var eventListeners = this._listeners[eventName];
  637. if (!eventListeners || eventListeners.length === 0) {
  638. return;
  639. }
  640. // Passing all arguments after the eventName to the listeners.
  641. var args = Array.prototype.slice.call(arguments, 1);
  642. // Making copy of the listeners array in case if it will be modified
  643. // during dispatch.
  644. eventListeners.slice(0).forEach(function (listener) {
  645. listener.apply(null, args);
  646. });
  647. }
  648. };
  649. return EventBus;
  650. })();
  651. var ProgressBar = (function ProgressBarClosure() {
  652. function clamp(v, min, max) {
  653. return Math.min(Math.max(v, min), max);
  654. }
  655. function ProgressBar(id, opts) {
  656. this.visible = true;
  657. // Fetch the sub-elements for later.
  658. this.div = document.querySelector(id + ' .progress');
  659. // Get the loading bar element, so it can be resized to fit the viewer.
  660. this.bar = this.div.parentNode;
  661. // Get options, with sensible defaults.
  662. this.height = opts.height || 100;
  663. this.width = opts.width || 100;
  664. this.units = opts.units || '%';
  665. // Initialize heights.
  666. this.div.style.height = this.height + this.units;
  667. this.percent = 0;
  668. }
  669. ProgressBar.prototype = {
  670. updateBar: function ProgressBar_updateBar() {
  671. if (this._indeterminate) {
  672. this.div.classList.add('indeterminate');
  673. this.div.style.width = this.width + this.units;
  674. return;
  675. }
  676. this.div.classList.remove('indeterminate');
  677. var progressSize = this.width * this._percent / 100;
  678. this.div.style.width = progressSize + this.units;
  679. },
  680. get percent() {
  681. return this._percent;
  682. },
  683. set percent(val) {
  684. this._indeterminate = isNaN(val);
  685. this._percent = clamp(val, 0, 100);
  686. this.updateBar();
  687. },
  688. setWidth: function ProgressBar_setWidth(viewer) {
  689. if (viewer) {
  690. var container = viewer.parentNode;
  691. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  692. if (scrollbarWidth > 0) {
  693. this.bar.setAttribute('style', 'width: calc(100% - ' +
  694. scrollbarWidth + 'px);');
  695. }
  696. }
  697. },
  698. hide: function ProgressBar_hide() {
  699. if (!this.visible) {
  700. return;
  701. }
  702. this.visible = false;
  703. this.bar.classList.add('hidden');
  704. document.body.classList.remove('loadingInProgress');
  705. },
  706. show: function ProgressBar_show() {
  707. if (this.visible) {
  708. return;
  709. }
  710. this.visible = true;
  711. document.body.classList.add('loadingInProgress');
  712. this.bar.classList.remove('hidden');
  713. }
  714. };
  715. return ProgressBar;
  716. })();
  717. exports.CSS_UNITS = CSS_UNITS;
  718. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  719. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  720. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  721. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  722. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  723. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  724. exports.mozL10n = mozL10n;
  725. exports.EventBus = EventBus;
  726. exports.ProgressBar = ProgressBar;
  727. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  728. exports.noContextMenuHandler = noContextMenuHandler;
  729. exports.parseQueryString = parseQueryString;
  730. exports.getVisibleElements = getVisibleElements;
  731. exports.roundToDivide = roundToDivide;
  732. exports.approximateFraction = approximateFraction;
  733. exports.getOutputScale = getOutputScale;
  734. exports.scrollIntoView = scrollIntoView;
  735. exports.watchScroll = watchScroll;
  736. exports.binarySearchFirstItem = binarySearchFirstItem;
  737. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  738. }));
  739. (function (root, factory) {
  740. {
  741. factory((root.pdfjsWebDOMEvents = {}), root.pdfjsWebUIUtils);
  742. }
  743. }(this, function (exports, uiUtils) {
  744. var EventBus = uiUtils.EventBus;
  745. // Attaching to the application event bus to dispatch events to the DOM for
  746. // backwards viewer API compatibility.
  747. function attachDOMEventsToEventBus(eventBus) {
  748. eventBus.on('documentload', function () {
  749. var event = document.createEvent('CustomEvent');
  750. event.initCustomEvent('documentload', true, true, {});
  751. window.dispatchEvent(event);
  752. });
  753. eventBus.on('pagerendered', function (e) {
  754. var event = document.createEvent('CustomEvent');
  755. event.initCustomEvent('pagerendered', true, true, {
  756. pageNumber: e.pageNumber,
  757. cssTransform: e.cssTransform,
  758. });
  759. e.source.div.dispatchEvent(event);
  760. });
  761. eventBus.on('textlayerrendered', function (e) {
  762. var event = document.createEvent('CustomEvent');
  763. event.initCustomEvent('textlayerrendered', true, true, {
  764. pageNumber: e.pageNumber
  765. });
  766. e.source.textLayerDiv.dispatchEvent(event);
  767. });
  768. eventBus.on('pagechange', function (e) {
  769. var event = document.createEvent('UIEvents');
  770. event.initUIEvent('pagechange', true, true, window, 0);
  771. event.pageNumber = e.pageNumber;
  772. e.source.container.dispatchEvent(event);
  773. });
  774. eventBus.on('pagesinit', function (e) {
  775. var event = document.createEvent('CustomEvent');
  776. event.initCustomEvent('pagesinit', true, true, null);
  777. e.source.container.dispatchEvent(event);
  778. });
  779. eventBus.on('pagesloaded', function (e) {
  780. var event = document.createEvent('CustomEvent');
  781. event.initCustomEvent('pagesloaded', true, true, {
  782. pagesCount: e.pagesCount
  783. });
  784. e.source.container.dispatchEvent(event);
  785. });
  786. eventBus.on('scalechange', function (e) {
  787. var event = document.createEvent('UIEvents');
  788. event.initUIEvent('scalechange', true, true, window, 0);
  789. event.scale = e.scale;
  790. event.presetValue = e.presetValue;
  791. e.source.container.dispatchEvent(event);
  792. });
  793. eventBus.on('updateviewarea', function (e) {
  794. var event = document.createEvent('UIEvents');
  795. event.initUIEvent('updateviewarea', true, true, window, 0);
  796. event.location = e.location;
  797. e.source.container.dispatchEvent(event);
  798. });
  799. eventBus.on('find', function (e) {
  800. if (e.source === window) {
  801. return; // event comes from FirefoxCom, no need to replicate
  802. }
  803. var event = document.createEvent('CustomEvent');
  804. event.initCustomEvent('find' + e.type, true, true, {
  805. query: e.query,
  806. phraseSearch: e.phraseSearch,
  807. caseSensitive: e.caseSensitive,
  808. highlightAll: e.highlightAll,
  809. findPrevious: e.findPrevious
  810. });
  811. window.dispatchEvent(event);
  812. });
  813. eventBus.on('attachmentsloaded', function (e) {
  814. var event = document.createEvent('CustomEvent');
  815. event.initCustomEvent('attachmentsloaded', true, true, {
  816. attachmentsCount: e.attachmentsCount
  817. });
  818. e.source.container.dispatchEvent(event);
  819. });
  820. eventBus.on('sidebarviewchanged', function (e) {
  821. var event = document.createEvent('CustomEvent');
  822. event.initCustomEvent('sidebarviewchanged', true, true, {
  823. view: e.view,
  824. });
  825. e.source.outerContainer.dispatchEvent(event);
  826. });
  827. eventBus.on('pagemode', function (e) {
  828. var event = document.createEvent('CustomEvent');
  829. event.initCustomEvent('pagemode', true, true, {
  830. mode: e.mode,
  831. });
  832. e.source.pdfViewer.container.dispatchEvent(event);
  833. });
  834. eventBus.on('namedaction', function (e) {
  835. var event = document.createEvent('CustomEvent');
  836. event.initCustomEvent('namedaction', true, true, {
  837. action: e.action
  838. });
  839. e.source.pdfViewer.container.dispatchEvent(event);
  840. });
  841. eventBus.on('presentationmodechanged', function (e) {
  842. var event = document.createEvent('CustomEvent');
  843. event.initCustomEvent('presentationmodechanged', true, true, {
  844. active: e.active,
  845. switchInProgress: e.switchInProgress
  846. });
  847. window.dispatchEvent(event);
  848. });
  849. eventBus.on('outlineloaded', function (e) {
  850. var event = document.createEvent('CustomEvent');
  851. event.initCustomEvent('outlineloaded', true, true, {
  852. outlineCount: e.outlineCount
  853. });
  854. e.source.container.dispatchEvent(event);
  855. });
  856. }
  857. var globalEventBus = null;
  858. function getGlobalEventBus() {
  859. if (globalEventBus) {
  860. return globalEventBus;
  861. }
  862. globalEventBus = new EventBus();
  863. attachDOMEventsToEventBus(globalEventBus);
  864. return globalEventBus;
  865. }
  866. exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus;
  867. exports.getGlobalEventBus = getGlobalEventBus;
  868. }));
  869. (function (root, factory) {
  870. {
  871. factory((root.pdfjsWebPDFFindController = {}), root.pdfjsWebUIUtils);
  872. }
  873. }(this, function (exports, uiUtils) {
  874. var scrollIntoView = uiUtils.scrollIntoView;
  875. var FindStates = {
  876. FIND_FOUND: 0,
  877. FIND_NOTFOUND: 1,
  878. FIND_WRAPPED: 2,
  879. FIND_PENDING: 3
  880. };
  881. var FIND_SCROLL_OFFSET_TOP = -50;
  882. var FIND_SCROLL_OFFSET_LEFT = -400;
  883. var CHARACTERS_TO_NORMALIZE = {
  884. '\u2018': '\'', // Left single quotation mark
  885. '\u2019': '\'', // Right single quotation mark
  886. '\u201A': '\'', // Single low-9 quotation mark
  887. '\u201B': '\'', // Single high-reversed-9 quotation mark
  888. '\u201C': '"', // Left double quotation mark
  889. '\u201D': '"', // Right double quotation mark
  890. '\u201E': '"', // Double low-9 quotation mark
  891. '\u201F': '"', // Double high-reversed-9 quotation mark
  892. '\u00BC': '1/4', // Vulgar fraction one quarter
  893. '\u00BD': '1/2', // Vulgar fraction one half
  894. '\u00BE': '3/4', // Vulgar fraction three quarters
  895. };
  896. /**
  897. * Provides "search" or "find" functionality for the PDF.
  898. * This object actually performs the search for a given string.
  899. */
  900. var PDFFindController = (function PDFFindControllerClosure() {
  901. function PDFFindController(options) {
  902. this.pdfViewer = options.pdfViewer || null;
  903. this.onUpdateResultsCount = null;
  904. this.onUpdateState = null;
  905. this.reset();
  906. // Compile the regular expression for text normalization once.
  907. var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
  908. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  909. }
  910. PDFFindController.prototype = {
  911. reset: function PDFFindController_reset() {
  912. this.startedTextExtraction = false;
  913. this.extractTextPromises = [];
  914. this.pendingFindMatches = Object.create(null);
  915. this.active = false; // If active, find results will be highlighted.
  916. this.pageContents = []; // Stores the text for each page.
  917. this.pageMatches = [];
  918. this.pageMatchesLength = null;
  919. this.matchCount = 0;
  920. this.selected = { // Currently selected match.
  921. pageIdx: -1,
  922. matchIdx: -1
  923. };
  924. this.offset = { // Where the find algorithm currently is in the document.
  925. pageIdx: null,
  926. matchIdx: null
  927. };
  928. this.pagesToSearch = null;
  929. this.resumePageIdx = null;
  930. this.state = null;
  931. this.dirtyMatch = false;
  932. this.findTimeout = null;
  933. this.firstPagePromise = new Promise(function (resolve) {
  934. this.resolveFirstPage = resolve;
  935. }.bind(this));
  936. },
  937. normalize: function PDFFindController_normalize(text) {
  938. return text.replace(this.normalizationRegex, function (ch) {
  939. return CHARACTERS_TO_NORMALIZE[ch];
  940. });
  941. },
  942. // Helper for multiple search - fills matchesWithLength array
  943. // and takes into account cases when one search term
  944. // include another search term (for example, "tamed tame" or "this is").
  945. // Looking for intersecting terms in the 'matches' and
  946. // leave elements with a longer match-length.
  947. _prepareMatches: function PDFFindController_prepareMatches(
  948. matchesWithLength, matches, matchesLength) {
  949. function isSubTerm(matchesWithLength, currentIndex) {
  950. var currentElem, prevElem, nextElem;
  951. currentElem = matchesWithLength[currentIndex];
  952. nextElem = matchesWithLength[currentIndex + 1];
  953. // checking for cases like "TAMEd TAME"
  954. if (currentIndex < matchesWithLength.length - 1 &&
  955. currentElem.match === nextElem.match) {
  956. currentElem.skipped = true;
  957. return true;
  958. }
  959. // checking for cases like "thIS IS"
  960. for (var i = currentIndex - 1; i >= 0; i--) {
  961. prevElem = matchesWithLength[i];
  962. if (prevElem.skipped) {
  963. continue;
  964. }
  965. if (prevElem.match + prevElem.matchLength < currentElem.match) {
  966. break;
  967. }
  968. if (prevElem.match + prevElem.matchLength >=
  969. currentElem.match + currentElem.matchLength) {
  970. currentElem.skipped = true;
  971. return true;
  972. }
  973. }
  974. return false;
  975. }
  976. var i, len;
  977. // Sorting array of objects { match: <match>, matchLength: <matchLength> }
  978. // in increasing index first and then the lengths.
  979. matchesWithLength.sort(function(a, b) {
  980. return a.match === b.match ?
  981. a.matchLength - b.matchLength : a.match - b.match;
  982. });
  983. for (i = 0, len = matchesWithLength.length; i < len; i++) {
  984. if (isSubTerm(matchesWithLength, i)) {
  985. continue;
  986. }
  987. matches.push(matchesWithLength[i].match);
  988. matchesLength.push(matchesWithLength[i].matchLength);
  989. }
  990. },
  991. calcFindPhraseMatch: function PDFFindController_calcFindPhraseMatch(
  992. query, pageIndex, pageContent) {
  993. var matches = [];
  994. var queryLen = query.length;
  995. var matchIdx = -queryLen;
  996. while (true) {
  997. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  998. if (matchIdx === -1) {
  999. break;
  1000. }
  1001. matches.push(matchIdx);
  1002. }
  1003. this.pageMatches[pageIndex] = matches;
  1004. },
  1005. calcFindWordMatch: function PDFFindController_calcFindWordMatch(
  1006. query, pageIndex, pageContent) {
  1007. var matchesWithLength = [];
  1008. // Divide the query into pieces and search for text on each piece.
  1009. var queryArray = query.match(/\S+/g);
  1010. var subquery, subqueryLen, matchIdx;
  1011. for (var i = 0, len = queryArray.length; i < len; i++) {
  1012. subquery = queryArray[i];
  1013. subqueryLen = subquery.length;
  1014. matchIdx = -subqueryLen;
  1015. while (true) {
  1016. matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen);
  1017. if (matchIdx === -1) {
  1018. break;
  1019. }
  1020. // Other searches do not, so we store the length.
  1021. matchesWithLength.push({
  1022. match: matchIdx,
  1023. matchLength: subqueryLen,
  1024. skipped: false
  1025. });
  1026. }
  1027. }
  1028. // Prepare arrays for store the matches.
  1029. if (!this.pageMatchesLength) {
  1030. this.pageMatchesLength = [];
  1031. }
  1032. this.pageMatchesLength[pageIndex] = [];
  1033. this.pageMatches[pageIndex] = [];
  1034. // Sort matchesWithLength, clean up intersecting terms
  1035. // and put the result into the two arrays.
  1036. this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex],
  1037. this.pageMatchesLength[pageIndex]);
  1038. },
  1039. calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
  1040. var pageContent = this.normalize(this.pageContents[pageIndex]);
  1041. var query = this.normalize(this.state.query);
  1042. var caseSensitive = this.state.caseSensitive;
  1043. var phraseSearch = this.state.phraseSearch;
  1044. var queryLen = query.length;
  1045. if (queryLen === 0) {
  1046. // Do nothing: the matches should be wiped out already.
  1047. return;
  1048. }
  1049. if (!caseSensitive) {
  1050. pageContent = pageContent.toLowerCase();
  1051. query = query.toLowerCase();
  1052. }
  1053. if (phraseSearch) {
  1054. this.calcFindPhraseMatch(query, pageIndex, pageContent);
  1055. } else {
  1056. this.calcFindWordMatch(query, pageIndex, pageContent);
  1057. }
  1058. this.updatePage(pageIndex);
  1059. if (this.resumePageIdx === pageIndex) {
  1060. this.resumePageIdx = null;
  1061. this.nextPageMatch();
  1062. }
  1063. // Update the matches count
  1064. if (this.pageMatches[pageIndex].length > 0) {
  1065. this.matchCount += this.pageMatches[pageIndex].length;
  1066. this.updateUIResultsCount();
  1067. }
  1068. },
  1069. extractText: function PDFFindController_extractText() {
  1070. if (this.startedTextExtraction) {
  1071. return;
  1072. }
  1073. this.startedTextExtraction = true;
  1074. this.pageContents = [];
  1075. var extractTextPromisesResolves = [];
  1076. var numPages = this.pdfViewer.pagesCount;
  1077. for (var i = 0; i < numPages; i++) {
  1078. this.extractTextPromises.push(new Promise(function (resolve) {
  1079. extractTextPromisesResolves.push(resolve);
  1080. }));
  1081. }
  1082. var self = this;
  1083. function extractPageText(pageIndex) {
  1084. self.pdfViewer.getPageTextContent(pageIndex).then(
  1085. function textContentResolved(textContent) {
  1086. var textItems = textContent.items;
  1087. var str = [];
  1088. for (var i = 0, len = textItems.length; i < len; i++) {
  1089. str.push(textItems[i].str);
  1090. }
  1091. // Store the pageContent as a string.
  1092. self.pageContents.push(str.join(''));
  1093. extractTextPromisesResolves[pageIndex](pageIndex);
  1094. if ((pageIndex + 1) < self.pdfViewer.pagesCount) {
  1095. extractPageText(pageIndex + 1);
  1096. }
  1097. }
  1098. );
  1099. }
  1100. extractPageText(0);
  1101. },
  1102. executeCommand: function PDFFindController_executeCommand(cmd, state) {
  1103. if (this.state === null || cmd !== 'findagain') {
  1104. this.dirtyMatch = true;
  1105. }
  1106. this.state = state;
  1107. this.updateUIState(FindStates.FIND_PENDING);
  1108. this.firstPagePromise.then(function() {
  1109. this.extractText();
  1110. clearTimeout(this.findTimeout);
  1111. if (cmd === 'find') {
  1112. // Only trigger the find action after 250ms of silence.
  1113. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
  1114. } else {
  1115. this.nextMatch();
  1116. }
  1117. }.bind(this));
  1118. },
  1119. updatePage: function PDFFindController_updatePage(index) {
  1120. if (this.selected.pageIdx === index) {
  1121. // If the page is selected, scroll the page into view, which triggers
  1122. // rendering the page, which adds the textLayer. Once the textLayer is
  1123. // build, it will scroll onto the selected match.
  1124. this.pdfViewer.currentPageNumber = index + 1;
  1125. }
  1126. var page = this.pdfViewer.getPageView(index);
  1127. if (page.textLayer) {
  1128. page.textLayer.updateMatches();
  1129. }
  1130. },
  1131. nextMatch: function PDFFindController_nextMatch() {
  1132. var previous = this.state.findPrevious;
  1133. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  1134. var numPages = this.pdfViewer.pagesCount;
  1135. this.active = true;
  1136. if (this.dirtyMatch) {
  1137. // Need to recalculate the matches, reset everything.
  1138. this.dirtyMatch = false;
  1139. this.selected.pageIdx = this.selected.matchIdx = -1;
  1140. this.offset.pageIdx = currentPageIndex;
  1141. this.offset.matchIdx = null;
  1142. this.hadMatch = false;
  1143. this.resumePageIdx = null;
  1144. this.pageMatches = [];
  1145. this.matchCount = 0;
  1146. this.pageMatchesLength = null;
  1147. var self = this;
  1148. for (var i = 0; i < numPages; i++) {
  1149. // Wipe out any previous highlighted matches.
  1150. this.updatePage(i);
  1151. // As soon as the text is extracted start finding the matches.
  1152. if (!(i in this.pendingFindMatches)) {
  1153. this.pendingFindMatches[i] = true;
  1154. this.extractTextPromises[i].then(function(pageIdx) {
  1155. delete self.pendingFindMatches[pageIdx];
  1156. self.calcFindMatch(pageIdx);
  1157. });
  1158. }
  1159. }
  1160. }
  1161. // If there's no query there's no point in searching.
  1162. if (this.state.query === '') {
  1163. this.updateUIState(FindStates.FIND_FOUND);
  1164. return;
  1165. }
  1166. // If we're waiting on a page, we return since we can't do anything else.
  1167. if (this.resumePageIdx) {
  1168. return;
  1169. }
  1170. var offset = this.offset;
  1171. // Keep track of how many pages we should maximally iterate through.
  1172. this.pagesToSearch = numPages;
  1173. // If there's already a matchIdx that means we are iterating through a
  1174. // page's matches.
  1175. if (offset.matchIdx !== null) {
  1176. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  1177. if ((!previous && offset.matchIdx + 1 < numPageMatches) ||
  1178. (previous && offset.matchIdx > 0)) {
  1179. // The simple case; we just have advance the matchIdx to select
  1180. // the next match on the page.
  1181. this.hadMatch = true;
  1182. offset.matchIdx = (previous ? offset.matchIdx - 1 :
  1183. offset.matchIdx + 1);
  1184. this.updateMatch(true);
  1185. return;
  1186. }
  1187. // We went beyond the current page's matches, so we advance to
  1188. // the next page.
  1189. this.advanceOffsetPage(previous);
  1190. }
  1191. // Start searching through the page.
  1192. this.nextPageMatch();
  1193. },
  1194. matchesReady: function PDFFindController_matchesReady(matches) {
  1195. var offset = this.offset;
  1196. var numMatches = matches.length;
  1197. var previous = this.state.findPrevious;
  1198. if (numMatches) {
  1199. // There were matches for the page, so initialize the matchIdx.
  1200. this.hadMatch = true;
  1201. offset.matchIdx = (previous ? numMatches - 1 : 0);
  1202. this.updateMatch(true);
  1203. return true;
  1204. } else {
  1205. // No matches, so attempt to search the next page.
  1206. this.advanceOffsetPage(previous);
  1207. if (offset.wrapped) {
  1208. offset.matchIdx = null;
  1209. if (this.pagesToSearch < 0) {
  1210. // No point in wrapping again, there were no matches.
  1211. this.updateMatch(false);
  1212. // while matches were not found, searching for a page
  1213. // with matches should nevertheless halt.
  1214. return true;
  1215. }
  1216. }
  1217. // Matches were not found (and searching is not done).
  1218. return false;
  1219. }
  1220. },
  1221. /**
  1222. * The method is called back from the text layer when match presentation
  1223. * is updated.
  1224. * @param {number} pageIndex - page index.
  1225. * @param {number} index - match index.
  1226. * @param {Array} elements - text layer div elements array.
  1227. * @param {number} beginIdx - start index of the div array for the match.
  1228. */
  1229. updateMatchPosition: function PDFFindController_updateMatchPosition(
  1230. pageIndex, index, elements, beginIdx) {
  1231. if (this.selected.matchIdx === index &&
  1232. this.selected.pageIdx === pageIndex) {
  1233. var spot = {
  1234. top: FIND_SCROLL_OFFSET_TOP,
  1235. left: FIND_SCROLL_OFFSET_LEFT
  1236. };
  1237. scrollIntoView(elements[beginIdx], spot,
  1238. /* skipOverflowHiddenElements = */ true);
  1239. }
  1240. },
  1241. nextPageMatch: function PDFFindController_nextPageMatch() {
  1242. if (this.resumePageIdx !== null) {
  1243. console.error('There can only be one pending page.');
  1244. }
  1245. do {
  1246. var pageIdx = this.offset.pageIdx;
  1247. var matches = this.pageMatches[pageIdx];
  1248. if (!matches) {
  1249. // The matches don't exist yet for processing by "matchesReady",
  1250. // so set a resume point for when they do exist.
  1251. this.resumePageIdx = pageIdx;
  1252. break;
  1253. }
  1254. } while (!this.matchesReady(matches));
  1255. },
  1256. advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
  1257. var offset = this.offset;
  1258. var numPages = this.extractTextPromises.length;
  1259. offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1);
  1260. offset.matchIdx = null;
  1261. this.pagesToSearch--;
  1262. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  1263. offset.pageIdx = (previous ? numPages - 1 : 0);
  1264. offset.wrapped = true;
  1265. }
  1266. },
  1267. updateMatch: function PDFFindController_updateMatch(found) {
  1268. var state = FindStates.FIND_NOTFOUND;
  1269. var wrapped = this.offset.wrapped;
  1270. this.offset.wrapped = false;
  1271. if (found) {
  1272. var previousPage = this.selected.pageIdx;
  1273. this.selected.pageIdx = this.offset.pageIdx;
  1274. this.selected.matchIdx = this.offset.matchIdx;
  1275. state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND);
  1276. // Update the currently selected page to wipe out any selected matches.
  1277. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  1278. this.updatePage(previousPage);
  1279. }
  1280. }
  1281. this.updateUIState(state, this.state.findPrevious);
  1282. if (this.selected.pageIdx !== -1) {
  1283. this.updatePage(this.selected.pageIdx);
  1284. }
  1285. },
  1286. updateUIResultsCount:
  1287. function PDFFindController_updateUIResultsCount() {
  1288. if (this.onUpdateResultsCount) {
  1289. this.onUpdateResultsCount(this.matchCount);
  1290. }
  1291. },
  1292. updateUIState: function PDFFindController_updateUIState(state, previous) {
  1293. if (this.onUpdateState) {
  1294. this.onUpdateState(state, previous, this.matchCount);
  1295. }
  1296. }
  1297. };
  1298. return PDFFindController;
  1299. })();
  1300. exports.FindStates = FindStates;
  1301. exports.PDFFindController = PDFFindController;
  1302. }));
  1303. (function (root, factory) {
  1304. {
  1305. factory((root.pdfjsWebPDFHistory = {}), root.pdfjsWebDOMEvents);
  1306. }
  1307. }(this, function (exports, domEvents) {
  1308. function PDFHistory(options) {
  1309. this.linkService = options.linkService;
  1310. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1311. this.initialized = false;
  1312. this.initialDestination = null;
  1313. this.initialBookmark = null;
  1314. }
  1315. PDFHistory.prototype = {
  1316. /**
  1317. * @param {string} fingerprint
  1318. */
  1319. initialize: function pdfHistoryInitialize(fingerprint) {
  1320. this.initialized = true;
  1321. this.reInitialized = false;
  1322. this.allowHashChange = true;
  1323. this.historyUnlocked = true;
  1324. this.isViewerInPresentationMode = false;
  1325. this.previousHash = window.location.hash.substring(1);
  1326. this.currentBookmark = '';
  1327. this.currentPage = 0;
  1328. this.updatePreviousBookmark = false;
  1329. this.previousBookmark = '';
  1330. this.previousPage = 0;
  1331. this.nextHashParam = '';
  1332. this.fingerprint = fingerprint;
  1333. this.currentUid = this.uid = 0;
  1334. this.current = {};
  1335. var state = window.history.state;
  1336. if (this._isStateObjectDefined(state)) {
  1337. // This corresponds to navigating back to the document
  1338. // from another page in the browser history.
  1339. if (state.target.dest) {
  1340. this.initialDestination = state.target.dest;
  1341. } else {
  1342. this.initialBookmark = state.target.hash;
  1343. }
  1344. this.currentUid = state.uid;
  1345. this.uid = state.uid + 1;
  1346. this.current = state.target;
  1347. } else {
  1348. // This corresponds to the loading of a new document.
  1349. if (state && state.fingerprint &&
  1350. this.fingerprint !== state.fingerprint) {
  1351. // Reinitialize the browsing history when a new document
  1352. // is opened in the web viewer.
  1353. this.reInitialized = true;
  1354. }
  1355. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  1356. }
  1357. var self = this;
  1358. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  1359. if (!self.historyUnlocked) {
  1360. return;
  1361. }
  1362. if (evt.state) {
  1363. // Move back/forward in the history.
  1364. self._goTo(evt.state);
  1365. return;
  1366. }
  1367. // If the state is not set, then the user tried to navigate to a
  1368. // different hash by manually editing the URL and pressing Enter, or by
  1369. // clicking on an in-page link (e.g. the "current view" link).
  1370. // Save the current view state to the browser history.
  1371. // Note: In Firefox, history.null could also be null after an in-page
  1372. // navigation to the same URL, and without dispatching the popstate
  1373. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  1374. if (self.uid === 0) {
  1375. // Replace the previous state if it was not explicitly set.
  1376. var previousParams = (self.previousHash && self.currentBookmark &&
  1377. self.previousHash !== self.currentBookmark) ?
  1378. {hash: self.currentBookmark, page: self.currentPage} :
  1379. {page: 1};
  1380. replacePreviousHistoryState(previousParams, function() {
  1381. updateHistoryWithCurrentHash();
  1382. });
  1383. } else {
  1384. updateHistoryWithCurrentHash();
  1385. }
  1386. }, false);
  1387. function updateHistoryWithCurrentHash() {
  1388. self.previousHash = window.location.hash.slice(1);
  1389. self._pushToHistory({hash: self.previousHash}, false, true);
  1390. self._updatePreviousBookmark();
  1391. }
  1392. function replacePreviousHistoryState(params, callback) {
  1393. // To modify the previous history entry, the following happens:
  1394. // 1. history.back()
  1395. // 2. _pushToHistory, which calls history.replaceState( ... )
  1396. // 3. history.forward()
  1397. // Because a navigation via the history API does not immediately update
  1398. // the history state, the popstate event is used for synchronization.
  1399. self.historyUnlocked = false;
  1400. // Suppress the hashchange event to avoid side effects caused by
  1401. // navigating back and forward.
  1402. self.allowHashChange = false;
  1403. window.addEventListener('popstate', rewriteHistoryAfterBack);
  1404. history.back();
  1405. function rewriteHistoryAfterBack() {
  1406. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  1407. window.addEventListener('popstate', rewriteHistoryAfterForward);
  1408. self._pushToHistory(params, false, true);
  1409. history.forward();
  1410. }
  1411. function rewriteHistoryAfterForward() {
  1412. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  1413. self.allowHashChange = true;
  1414. self.historyUnlocked = true;
  1415. callback();
  1416. }
  1417. }
  1418. function pdfHistoryBeforeUnload() {
  1419. var previousParams = self._getPreviousParams(null, true);
  1420. if (previousParams) {
  1421. var replacePrevious = (!self.current.dest &&
  1422. self.current.hash !== self.previousHash);
  1423. self._pushToHistory(previousParams, false, replacePrevious);
  1424. self._updatePreviousBookmark();
  1425. }
  1426. // Remove the event listener when navigating away from the document,
  1427. // since 'beforeunload' prevents Firefox from caching the document.
  1428. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  1429. false);
  1430. }
  1431. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1432. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  1433. // If the entire viewer (including the PDF file) is cached in
  1434. // the browser, we need to reattach the 'beforeunload' event listener
  1435. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  1436. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1437. }, false);
  1438. self.eventBus.on('presentationmodechanged', function(e) {
  1439. self.isViewerInPresentationMode = e.active;
  1440. });
  1441. },
  1442. clearHistoryState: function pdfHistory_clearHistoryState() {
  1443. this._pushOrReplaceState(null, true);
  1444. },
  1445. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  1446. return (state && state.uid >= 0 &&
  1447. state.fingerprint && this.fingerprint === state.fingerprint &&
  1448. state.target && state.target.hash) ? true : false;
  1449. },
  1450. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  1451. replace) {
  1452. if (replace) {
  1453. window.history.replaceState(stateObj, '', document.URL);
  1454. } else {
  1455. window.history.pushState(stateObj, '', document.URL);
  1456. }
  1457. },
  1458. get isHashChangeUnlocked() {
  1459. if (!this.initialized) {
  1460. return true;
  1461. }
  1462. return this.allowHashChange;
  1463. },
  1464. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  1465. if (this.updatePreviousBookmark &&
  1466. this.currentBookmark && this.currentPage) {
  1467. this.previousBookmark = this.currentBookmark;
  1468. this.previousPage = this.currentPage;
  1469. this.updatePreviousBookmark = false;
  1470. }
  1471. },
  1472. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  1473. pageNum) {
  1474. if (this.initialized) {
  1475. this.currentBookmark = bookmark.substring(1);
  1476. this.currentPage = pageNum | 0;
  1477. this._updatePreviousBookmark();
  1478. }
  1479. },
  1480. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  1481. if (this.initialized) {
  1482. this.nextHashParam = param;
  1483. }
  1484. },
  1485. push: function pdfHistoryPush(params, isInitialBookmark) {
  1486. if (!(this.initialized && this.historyUnlocked)) {
  1487. return;
  1488. }
  1489. if (params.dest && !params.hash) {
  1490. params.hash = (this.current.hash && this.current.dest &&
  1491. this.current.dest === params.dest) ?
  1492. this.current.hash :
  1493. this.linkService.getDestinationHash(params.dest).split('#')[1];
  1494. }
  1495. if (params.page) {
  1496. params.page |= 0;
  1497. }
  1498. if (isInitialBookmark) {
  1499. var target = window.history.state.target;
  1500. if (!target) {
  1501. // Invoked when the user specifies an initial bookmark,
  1502. // thus setting initialBookmark, when the document is loaded.
  1503. this._pushToHistory(params, false);
  1504. this.previousHash = window.location.hash.substring(1);
  1505. }
  1506. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  1507. if (target) {
  1508. // If the current document is reloaded,
  1509. // avoid creating duplicate entries in the history.
  1510. this._updatePreviousBookmark();
  1511. }
  1512. return;
  1513. }
  1514. if (this.nextHashParam) {
  1515. if (this.nextHashParam === params.hash) {
  1516. this.nextHashParam = null;
  1517. this.updatePreviousBookmark = true;
  1518. return;
  1519. } else {
  1520. this.nextHashParam = null;
  1521. }
  1522. }
  1523. if (params.hash) {
  1524. if (this.current.hash) {
  1525. if (this.current.hash !== params.hash) {
  1526. this._pushToHistory(params, true);
  1527. } else {
  1528. if (!this.current.page && params.page) {
  1529. this._pushToHistory(params, false, true);
  1530. }
  1531. this.updatePreviousBookmark = true;
  1532. }
  1533. } else {
  1534. this._pushToHistory(params, true);
  1535. }
  1536. } else if (this.current.page && params.page &&
  1537. this.current.page !== params.page) {
  1538. this._pushToHistory(params, true);
  1539. }
  1540. },
  1541. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  1542. beforeUnload) {
  1543. if (!(this.currentBookmark && this.currentPage)) {
  1544. return null;
  1545. } else if (this.updatePreviousBookmark) {
  1546. this.updatePreviousBookmark = false;
  1547. }
  1548. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  1549. // Prevent the history from getting stuck in the current state,
  1550. // effectively preventing the user from going back/forward in
  1551. // the history.
  1552. //
  1553. // This happens if the current position in the document didn't change
  1554. // when the history was previously updated. The reasons for this are
  1555. // either:
  1556. // 1. The current zoom value is such that the document does not need to,
  1557. // or cannot, be scrolled to display the destination.
  1558. // 2. The previous destination is broken, and doesn't actally point to a
  1559. // position within the document.
  1560. // (This is either due to a bad PDF generator, or the user making a
  1561. // mistake when entering a destination in the hash parameters.)
  1562. return null;
  1563. }
  1564. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  1565. if (this.previousBookmark === this.currentBookmark) {
  1566. return null;
  1567. }
  1568. } else if (this.current.page || onlyCheckPage) {
  1569. if (this.previousPage === this.currentPage) {
  1570. return null;
  1571. }
  1572. } else {
  1573. return null;
  1574. }
  1575. var params = {hash: this.currentBookmark, page: this.currentPage};
  1576. if (this.isViewerInPresentationMode) {
  1577. params.hash = null;
  1578. }
  1579. return params;
  1580. },
  1581. _stateObj: function pdfHistory_stateObj(params) {
  1582. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  1583. },
  1584. _pushToHistory: function pdfHistory_pushToHistory(params,
  1585. addPrevious, overwrite) {
  1586. if (!this.initialized) {
  1587. return;
  1588. }
  1589. if (!params.hash && params.page) {
  1590. params.hash = ('page=' + params.page);
  1591. }
  1592. if (addPrevious && !overwrite) {
  1593. var previousParams = this._getPreviousParams();
  1594. if (previousParams) {
  1595. var replacePrevious = (!this.current.dest &&
  1596. this.current.hash !== this.previousHash);
  1597. this._pushToHistory(previousParams, false, replacePrevious);
  1598. }
  1599. }
  1600. this._pushOrReplaceState(this._stateObj(params),
  1601. (overwrite || this.uid === 0));
  1602. this.currentUid = this.uid++;
  1603. this.current = params;
  1604. this.updatePreviousBookmark = true;
  1605. },
  1606. _goTo: function pdfHistory_goTo(state) {
  1607. if (!(this.initialized && this.historyUnlocked &&
  1608. this._isStateObjectDefined(state))) {
  1609. return;
  1610. }
  1611. if (!this.reInitialized && state.uid < this.currentUid) {
  1612. var previousParams = this._getPreviousParams(true);
  1613. if (previousParams) {
  1614. this._pushToHistory(this.current, false);
  1615. this._pushToHistory(previousParams, false);
  1616. this.currentUid = state.uid;
  1617. window.history.back();
  1618. return;
  1619. }
  1620. }
  1621. this.historyUnlocked = false;
  1622. if (state.target.dest) {
  1623. this.linkService.navigateTo(state.target.dest);
  1624. } else {
  1625. this.linkService.setHash(state.target.hash);
  1626. }
  1627. this.currentUid = state.uid;
  1628. if (state.uid > this.uid) {
  1629. this.uid = state.uid;
  1630. }
  1631. this.current = state.target;
  1632. this.updatePreviousBookmark = true;
  1633. var currentHash = window.location.hash.substring(1);
  1634. if (this.previousHash !== currentHash) {
  1635. this.allowHashChange = false;
  1636. }
  1637. this.previousHash = currentHash;
  1638. this.historyUnlocked = true;
  1639. },
  1640. back: function pdfHistoryBack() {
  1641. this.go(-1);
  1642. },
  1643. forward: function pdfHistoryForward() {
  1644. this.go(1);
  1645. },
  1646. go: function pdfHistoryGo(direction) {
  1647. if (this.initialized && this.historyUnlocked) {
  1648. var state = window.history.state;
  1649. if (direction === -1 && state && state.uid > 0) {
  1650. window.history.back();
  1651. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  1652. window.history.forward();
  1653. }
  1654. }
  1655. }
  1656. };
  1657. exports.PDFHistory = PDFHistory;
  1658. }));
  1659. (function (root, factory) {
  1660. {
  1661. factory((root.pdfjsWebPDFLinkService = {}), root.pdfjsWebUIUtils,
  1662. root.pdfjsWebDOMEvents);
  1663. }
  1664. }(this, function (exports, uiUtils, domEvents) {
  1665. var parseQueryString = uiUtils.parseQueryString;
  1666. var PageNumberRegExp = /^\d+$/;
  1667. function isPageNumber(str) {
  1668. return PageNumberRegExp.test(str);
  1669. }
  1670. /**
  1671. * @typedef {Object} PDFLinkServiceOptions
  1672. * @property {EventBus} eventBus - The application event bus.
  1673. */
  1674. /**
  1675. * Performs navigation functions inside PDF, such as opening specified page,
  1676. * or destination.
  1677. * @class
  1678. * @implements {IPDFLinkService}
  1679. */
  1680. var PDFLinkService = (function PDFLinkServiceClosure() {
  1681. /**
  1682. * @constructs PDFLinkService
  1683. * @param {PDFLinkServiceOptions} options
  1684. */
  1685. function PDFLinkService(options) {
  1686. options = options || {};
  1687. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1688. this.baseUrl = null;
  1689. this.pdfDocument = null;
  1690. this.pdfViewer = null;
  1691. this.pdfHistory = null;
  1692. this._pagesRefCache = null;
  1693. }
  1694. PDFLinkService.prototype = {
  1695. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  1696. this.baseUrl = baseUrl;
  1697. this.pdfDocument = pdfDocument;
  1698. this._pagesRefCache = Object.create(null);
  1699. },
  1700. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  1701. this.pdfViewer = pdfViewer;
  1702. },
  1703. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  1704. this.pdfHistory = pdfHistory;
  1705. },
  1706. /**
  1707. * @returns {number}
  1708. */
  1709. get pagesCount() {
  1710. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  1711. },
  1712. /**
  1713. * @returns {number}
  1714. */
  1715. get page() {
  1716. return this.pdfViewer.currentPageNumber;
  1717. },
  1718. /**
  1719. * @param {number} value
  1720. */
  1721. set page(value) {
  1722. this.pdfViewer.currentPageNumber = value;
  1723. },
  1724. /**
  1725. * @param dest - The PDF destination object.
  1726. */
  1727. navigateTo: function PDFLinkService_navigateTo(dest) {
  1728. var destString = '';
  1729. var self = this;
  1730. var goToDestination = function(destRef) {
  1731. // dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
  1732. var pageNumber = destRef instanceof Object ?
  1733. self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  1734. (destRef + 1);
  1735. if (pageNumber) {
  1736. if (pageNumber > self.pagesCount) {
  1737. console.error('PDFLinkService_navigateTo: ' +
  1738. 'Trying to navigate to a non-existent page.');
  1739. return;
  1740. }
  1741. self.pdfViewer.scrollPageIntoView({
  1742. pageNumber: pageNumber,
  1743. destArray: dest,
  1744. });
  1745. if (self.pdfHistory) {
  1746. // Update the browsing history.
  1747. self.pdfHistory.push({
  1748. dest: dest,
  1749. hash: destString,
  1750. page: pageNumber
  1751. });
  1752. }
  1753. } else {
  1754. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  1755. var pageNum = pageIndex + 1;
  1756. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  1757. self._pagesRefCache[cacheKey] = pageNum;
  1758. goToDestination(destRef);
  1759. });
  1760. }
  1761. };
  1762. var destinationPromise;
  1763. if (typeof dest === 'string') {
  1764. destString = dest;
  1765. destinationPromise = this.pdfDocument.getDestination(dest);
  1766. } else {
  1767. destinationPromise = Promise.resolve(dest);
  1768. }
  1769. destinationPromise.then(function(destination) {
  1770. dest = destination;
  1771. if (!(destination instanceof Array)) {
  1772. return; // invalid destination
  1773. }
  1774. goToDestination(destination[0]);
  1775. });
  1776. },
  1777. /**
  1778. * @param dest - The PDF destination object.
  1779. * @returns {string} The hyperlink to the PDF object.
  1780. */
  1781. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  1782. if (typeof dest === 'string') {
  1783. // In practice, a named destination may contain only a number.
  1784. // If that happens, use the '#nameddest=' form to avoid the link
  1785. // redirecting to a page, instead of the correct destination.
  1786. return this.getAnchorUrl(
  1787. '#' + (isPageNumber(dest) ? 'nameddest=' : '') + escape(dest));
  1788. }
  1789. if (dest instanceof Array) {
  1790. var str = JSON.stringify(dest);
  1791. return this.getAnchorUrl('#' + escape(str));
  1792. }
  1793. return this.getAnchorUrl('');
  1794. },
  1795. /**
  1796. * Prefix the full url on anchor links to make sure that links are resolved
  1797. * relative to the current URL instead of the one defined in <base href>.
  1798. * @param {String} anchor The anchor hash, including the #.
  1799. * @returns {string} The hyperlink to the PDF object.
  1800. */
  1801. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  1802. return (this.baseUrl || '') + anchor;
  1803. },
  1804. /**
  1805. * @param {string} hash
  1806. */
  1807. setHash: function PDFLinkService_setHash(hash) {
  1808. var pageNumber, dest;
  1809. if (hash.indexOf('=') >= 0) {
  1810. var params = parseQueryString(hash);
  1811. if ('search' in params) {
  1812. this.eventBus.dispatch('findfromurlhash', {
  1813. source: this,
  1814. query: params['search'].replace(/"/g, ''),
  1815. phraseSearch: (params['phrase'] === 'true')
  1816. });
  1817. }
  1818. // borrowing syntax from "Parameters for Opening PDF Files"
  1819. if ('nameddest' in params) {
  1820. if (this.pdfHistory) {
  1821. this.pdfHistory.updateNextHashParam(params.nameddest);
  1822. }
  1823. this.navigateTo(params.nameddest);
  1824. return;
  1825. }
  1826. if ('page' in params) {
  1827. pageNumber = (params.page | 0) || 1;
  1828. }
  1829. if ('zoom' in params) {
  1830. // Build the destination array.
  1831. var zoomArgs = params.zoom.split(','); // scale,left,top
  1832. var zoomArg = zoomArgs[0];
  1833. var zoomArgNumber = parseFloat(zoomArg);
  1834. if (zoomArg.indexOf('Fit') === -1) {
  1835. // If the zoomArg is a number, it has to get divided by 100. If it's
  1836. // a string, it should stay as it is.
  1837. dest = [null, { name: 'XYZ' },
  1838. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  1839. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  1840. (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
  1841. } else {
  1842. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  1843. dest = [null, { name: zoomArg }];
  1844. } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
  1845. (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  1846. dest = [null, { name: zoomArg },
  1847. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
  1848. } else if (zoomArg === 'FitR') {
  1849. if (zoomArgs.length !== 5) {
  1850. console.error('PDFLinkService_setHash: ' +
  1851. 'Not enough parameters for \'FitR\'.');
  1852. } else {
  1853. dest = [null, { name: zoomArg },
  1854. (zoomArgs[1] | 0), (zoomArgs[2] | 0),
  1855. (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
  1856. }
  1857. } else {
  1858. console.error('PDFLinkService_setHash: \'' + zoomArg +
  1859. '\' is not a valid zoom value.');
  1860. }
  1861. }
  1862. }
  1863. if (dest) {
  1864. this.pdfViewer.scrollPageIntoView({
  1865. pageNumber: pageNumber || this.page,
  1866. destArray: dest,
  1867. allowNegativeOffset: true,
  1868. });
  1869. } else if (pageNumber) {
  1870. this.page = pageNumber; // simple page
  1871. }
  1872. if ('pagemode' in params) {
  1873. this.eventBus.dispatch('pagemode', {
  1874. source: this,
  1875. mode: params.pagemode
  1876. });
  1877. }
  1878. } else if (isPageNumber(hash)) { // Page number.
  1879. this.page = hash | 0;
  1880. } else { // Named (or explicit) destination.
  1881. dest = unescape(hash);
  1882. try {
  1883. dest = JSON.parse(dest);
  1884. } catch (ex) {}
  1885. if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
  1886. if (this.pdfHistory) {
  1887. this.pdfHistory.updateNextHashParam(dest);
  1888. }
  1889. this.navigateTo(dest);
  1890. return;
  1891. }
  1892. console.error('PDFLinkService_setHash: \'' + unescape(hash) +
  1893. '\' is not a valid destination.');
  1894. }
  1895. },
  1896. /**
  1897. * @param {string} action
  1898. */
  1899. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  1900. // See PDF reference, table 8.45 - Named action
  1901. switch (action) {
  1902. case 'GoBack':
  1903. if (this.pdfHistory) {
  1904. this.pdfHistory.back();
  1905. }
  1906. break;
  1907. case 'GoForward':
  1908. if (this.pdfHistory) {
  1909. this.pdfHistory.forward();
  1910. }
  1911. break;
  1912. case 'NextPage':
  1913. if (this.page < this.pagesCount) {
  1914. this.page++;
  1915. }
  1916. break;
  1917. case 'PrevPage':
  1918. if (this.page > 1) {
  1919. this.page--;
  1920. }
  1921. break;
  1922. case 'LastPage':
  1923. this.page = this.pagesCount;
  1924. break;
  1925. case 'FirstPage':
  1926. this.page = 1;
  1927. break;
  1928. default:
  1929. break; // No action according to spec
  1930. }
  1931. this.eventBus.dispatch('namedaction', {
  1932. source: this,
  1933. action: action
  1934. });
  1935. },
  1936. /**
  1937. * @param {number} pageNum - page number.
  1938. * @param {Object} pageRef - reference to the page.
  1939. */
  1940. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  1941. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1942. this._pagesRefCache[refStr] = pageNum;
  1943. }
  1944. };
  1945. function isValidExplicitDestination(dest) {
  1946. if (!(dest instanceof Array)) {
  1947. return false;
  1948. }
  1949. var destLength = dest.length, allowNull = true;
  1950. if (destLength < 2) {
  1951. return false;
  1952. }
  1953. var page = dest[0];
  1954. if (!(typeof page === 'object' &&
  1955. typeof page.num === 'number' && (page.num | 0) === page.num &&
  1956. typeof page.gen === 'number' && (page.gen | 0) === page.gen) &&
  1957. !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
  1958. return false;
  1959. }
  1960. var zoom = dest[1];
  1961. if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
  1962. return false;
  1963. }
  1964. switch (zoom.name) {
  1965. case 'XYZ':
  1966. if (destLength !== 5) {
  1967. return false;
  1968. }
  1969. break;
  1970. case 'Fit':
  1971. case 'FitB':
  1972. return destLength === 2;
  1973. case 'FitH':
  1974. case 'FitBH':
  1975. case 'FitV':
  1976. case 'FitBV':
  1977. if (destLength !== 3) {
  1978. return false;
  1979. }
  1980. break;
  1981. case 'FitR':
  1982. if (destLength !== 6) {
  1983. return false;
  1984. }
  1985. allowNull = false;
  1986. break;
  1987. default:
  1988. return false;
  1989. }
  1990. for (var i = 2; i < destLength; i++) {
  1991. var param = dest[i];
  1992. if (!(typeof param === 'number' || (allowNull && param === null))) {
  1993. return false;
  1994. }
  1995. }
  1996. return true;
  1997. }
  1998. return PDFLinkService;
  1999. })();
  2000. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  2001. function SimpleLinkService() {}
  2002. SimpleLinkService.prototype = {
  2003. /**
  2004. * @returns {number}
  2005. */
  2006. get page() {
  2007. return 0;
  2008. },
  2009. /**
  2010. * @param {number} value
  2011. */
  2012. set page(value) {},
  2013. /**
  2014. * @param dest - The PDF destination object.
  2015. */
  2016. navigateTo: function (dest) {},
  2017. /**
  2018. * @param dest - The PDF destination object.
  2019. * @returns {string} The hyperlink to the PDF object.
  2020. */
  2021. getDestinationHash: function (dest) {
  2022. return '#';
  2023. },
  2024. /**
  2025. * @param hash - The PDF parameters/hash.
  2026. * @returns {string} The hyperlink to the PDF object.
  2027. */
  2028. getAnchorUrl: function (hash) {
  2029. return '#';
  2030. },
  2031. /**
  2032. * @param {string} hash
  2033. */
  2034. setHash: function (hash) {},
  2035. /**
  2036. * @param {string} action
  2037. */
  2038. executeNamedAction: function (action) {},
  2039. /**
  2040. * @param {number} pageNum - page number.
  2041. * @param {Object} pageRef - reference to the page.
  2042. */
  2043. cachePageRef: function (pageNum, pageRef) {}
  2044. };
  2045. return SimpleLinkService;
  2046. })();
  2047. exports.PDFLinkService = PDFLinkService;
  2048. exports.SimpleLinkService = SimpleLinkService;
  2049. }));
  2050. (function (root, factory) {
  2051. {
  2052. factory((root.pdfjsWebPDFPageView = {}), root.pdfjsWebUIUtils,
  2053. root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents,
  2054. root.pdfjsWebPDFJS);
  2055. }
  2056. }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) {
  2057. var CSS_UNITS = uiUtils.CSS_UNITS;
  2058. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2059. var getOutputScale = uiUtils.getOutputScale;
  2060. var approximateFraction = uiUtils.approximateFraction;
  2061. var roundToDivide = uiUtils.roundToDivide;
  2062. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2063. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  2064. /**
  2065. * @typedef {Object} PDFPageViewOptions
  2066. * @property {HTMLDivElement} container - The viewer element.
  2067. * @property {EventBus} eventBus - The application event bus.
  2068. * @property {number} id - The page unique ID (normally its number).
  2069. * @property {number} scale - The page scale display.
  2070. * @property {PageViewport} defaultViewport - The page viewport.
  2071. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  2072. * @property {IPDFTextLayerFactory} textLayerFactory
  2073. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  2074. * @property {boolean} enhanceTextSelection - Turns on the text selection
  2075. * enhancement. The default is `false`.
  2076. * @property {boolean} renderInteractiveForms - Turns on rendering of
  2077. * interactive form elements. The default is `false`.
  2078. */
  2079. /**
  2080. * @class
  2081. * @implements {IRenderableView}
  2082. */
  2083. var PDFPageView = (function PDFPageViewClosure() {
  2084. /**
  2085. * @constructs PDFPageView
  2086. * @param {PDFPageViewOptions} options
  2087. */
  2088. function PDFPageView(options) {
  2089. var container = options.container;
  2090. var id = options.id;
  2091. var scale = options.scale;
  2092. var defaultViewport = options.defaultViewport;
  2093. var renderingQueue = options.renderingQueue;
  2094. var textLayerFactory = options.textLayerFactory;
  2095. var annotationLayerFactory = options.annotationLayerFactory;
  2096. var enhanceTextSelection = options.enhanceTextSelection || false;
  2097. var renderInteractiveForms = options.renderInteractiveForms || false;
  2098. this.id = id;
  2099. this.renderingId = 'page' + id;
  2100. this.rotation = 0;
  2101. this.scale = scale || DEFAULT_SCALE;
  2102. this.viewport = defaultViewport;
  2103. this.pdfPageRotate = defaultViewport.rotation;
  2104. this.hasRestrictedScaling = false;
  2105. this.enhanceTextSelection = enhanceTextSelection;
  2106. this.renderInteractiveForms = renderInteractiveForms;
  2107. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2108. this.renderingQueue = renderingQueue;
  2109. this.textLayerFactory = textLayerFactory;
  2110. this.annotationLayerFactory = annotationLayerFactory;
  2111. this.renderingState = RenderingStates.INITIAL;
  2112. this.resume = null;
  2113. this.onBeforeDraw = null;
  2114. this.onAfterDraw = null;
  2115. this.textLayer = null;
  2116. this.zoomLayer = null;
  2117. this.annotationLayer = null;
  2118. var div = document.createElement('div');
  2119. div.id = 'pageContainer' + this.id;
  2120. div.className = 'page';
  2121. div.style.width = Math.floor(this.viewport.width) + 'px';
  2122. div.style.height = Math.floor(this.viewport.height) + 'px';
  2123. div.setAttribute('data-page-number', this.id);
  2124. this.div = div;
  2125. container.appendChild(div);
  2126. }
  2127. PDFPageView.prototype = {
  2128. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  2129. this.pdfPage = pdfPage;
  2130. this.pdfPageRotate = pdfPage.rotate;
  2131. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2132. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  2133. totalRotation);
  2134. this.stats = pdfPage.stats;
  2135. this.reset();
  2136. },
  2137. destroy: function PDFPageView_destroy() {
  2138. this.zoomLayer = null;
  2139. this.reset();
  2140. if (this.pdfPage) {
  2141. this.pdfPage.cleanup();
  2142. }
  2143. },
  2144. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  2145. if (this.renderTask) {
  2146. this.renderTask.cancel();
  2147. }
  2148. this.resume = null;
  2149. this.renderingState = RenderingStates.INITIAL;
  2150. var div = this.div;
  2151. div.style.width = Math.floor(this.viewport.width) + 'px';
  2152. div.style.height = Math.floor(this.viewport.height) + 'px';
  2153. var childNodes = div.childNodes;
  2154. var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
  2155. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  2156. this.annotationLayer.div) || null;
  2157. for (var i = childNodes.length - 1; i >= 0; i--) {
  2158. var node = childNodes[i];
  2159. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  2160. continue;
  2161. }
  2162. div.removeChild(node);
  2163. }
  2164. div.removeAttribute('data-loaded');
  2165. if (currentAnnotationNode) {
  2166. // Hide annotationLayer until all elements are resized
  2167. // so they are not displayed on the already-resized page
  2168. this.annotationLayer.hide();
  2169. } else {
  2170. this.annotationLayer = null;
  2171. }
  2172. if (this.canvas && !currentZoomLayerNode) {
  2173. // Zeroing the width and height causes Firefox to release graphics
  2174. // resources immediately, which can greatly reduce memory consumption.
  2175. this.canvas.width = 0;
  2176. this.canvas.height = 0;
  2177. delete this.canvas;
  2178. }
  2179. this.loadingIconDiv = document.createElement('div');
  2180. this.loadingIconDiv.className = 'loadingIcon';
  2181. div.appendChild(this.loadingIconDiv);
  2182. },
  2183. update: function PDFPageView_update(scale, rotation) {
  2184. this.scale = scale || this.scale;
  2185. if (typeof rotation !== 'undefined') {
  2186. this.rotation = rotation;
  2187. }
  2188. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2189. this.viewport = this.viewport.clone({
  2190. scale: this.scale * CSS_UNITS,
  2191. rotation: totalRotation
  2192. });
  2193. var isScalingRestricted = false;
  2194. if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2195. var outputScale = this.outputScale;
  2196. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  2197. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  2198. pdfjsLib.PDFJS.maxCanvasPixels) {
  2199. isScalingRestricted = true;
  2200. }
  2201. }
  2202. if (this.canvas) {
  2203. if (pdfjsLib.PDFJS.useOnlyCssZoom ||
  2204. (this.hasRestrictedScaling && isScalingRestricted)) {
  2205. this.cssTransform(this.canvas, true);
  2206. this.eventBus.dispatch('pagerendered', {
  2207. source: this,
  2208. pageNumber: this.id,
  2209. cssTransform: true,
  2210. });
  2211. return;
  2212. }
  2213. if (!this.zoomLayer) {
  2214. this.zoomLayer = this.canvas.parentNode;
  2215. this.zoomLayer.style.position = 'absolute';
  2216. }
  2217. }
  2218. if (this.zoomLayer) {
  2219. this.cssTransform(this.zoomLayer.firstChild);
  2220. }
  2221. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
  2222. },
  2223. /**
  2224. * Called when moved in the parent's container.
  2225. */
  2226. updatePosition: function PDFPageView_updatePosition() {
  2227. if (this.textLayer) {
  2228. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2229. }
  2230. },
  2231. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  2232. var CustomStyle = pdfjsLib.CustomStyle;
  2233. // Scale canvas, canvas wrapper, and page container.
  2234. var width = this.viewport.width;
  2235. var height = this.viewport.height;
  2236. var div = this.div;
  2237. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  2238. Math.floor(width) + 'px';
  2239. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  2240. Math.floor(height) + 'px';
  2241. // The canvas may have been originally rotated, rotate relative to that.
  2242. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  2243. var absRotation = Math.abs(relativeRotation);
  2244. var scaleX = 1, scaleY = 1;
  2245. if (absRotation === 90 || absRotation === 270) {
  2246. // Scale x and y because of the rotation.
  2247. scaleX = height / width;
  2248. scaleY = width / height;
  2249. }
  2250. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  2251. 'scale(' + scaleX + ',' + scaleY + ')';
  2252. CustomStyle.setProp('transform', canvas, cssTransform);
  2253. if (this.textLayer) {
  2254. // Rotating the text layer is more complicated since the divs inside the
  2255. // the text layer are rotated.
  2256. // TODO: This could probably be simplified by drawing the text layer in
  2257. // one orientation then rotating overall.
  2258. var textLayerViewport = this.textLayer.viewport;
  2259. var textRelativeRotation = this.viewport.rotation -
  2260. textLayerViewport.rotation;
  2261. var textAbsRotation = Math.abs(textRelativeRotation);
  2262. var scale = width / textLayerViewport.width;
  2263. if (textAbsRotation === 90 || textAbsRotation === 270) {
  2264. scale = width / textLayerViewport.height;
  2265. }
  2266. var textLayerDiv = this.textLayer.textLayerDiv;
  2267. var transX, transY;
  2268. switch (textAbsRotation) {
  2269. case 0:
  2270. transX = transY = 0;
  2271. break;
  2272. case 90:
  2273. transX = 0;
  2274. transY = '-' + textLayerDiv.style.height;
  2275. break;
  2276. case 180:
  2277. transX = '-' + textLayerDiv.style.width;
  2278. transY = '-' + textLayerDiv.style.height;
  2279. break;
  2280. case 270:
  2281. transX = '-' + textLayerDiv.style.width;
  2282. transY = 0;
  2283. break;
  2284. default:
  2285. console.error('Bad rotation value.');
  2286. break;
  2287. }
  2288. CustomStyle.setProp('transform', textLayerDiv,
  2289. 'rotate(' + textAbsRotation + 'deg) ' +
  2290. 'scale(' + scale + ', ' + scale + ') ' +
  2291. 'translate(' + transX + ', ' + transY + ')');
  2292. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  2293. }
  2294. if (redrawAnnotations && this.annotationLayer) {
  2295. this.annotationLayer.render(this.viewport, 'display');
  2296. }
  2297. },
  2298. get width() {
  2299. return this.viewport.width;
  2300. },
  2301. get height() {
  2302. return this.viewport.height;
  2303. },
  2304. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  2305. return this.viewport.convertToPdfPoint(x, y);
  2306. },
  2307. draw: function PDFPageView_draw() {
  2308. if (this.renderingState !== RenderingStates.INITIAL) {
  2309. console.error('Must be in new state before drawing');
  2310. }
  2311. this.renderingState = RenderingStates.RUNNING;
  2312. var pdfPage = this.pdfPage;
  2313. var viewport = this.viewport;
  2314. var div = this.div;
  2315. // Wrap the canvas so if it has a css transform for highdpi the overflow
  2316. // will be hidden in FF.
  2317. var canvasWrapper = document.createElement('div');
  2318. canvasWrapper.style.width = div.style.width;
  2319. canvasWrapper.style.height = div.style.height;
  2320. canvasWrapper.classList.add('canvasWrapper');
  2321. var canvas = document.createElement('canvas');
  2322. canvas.id = 'page' + this.id;
  2323. // Keep the canvas hidden until the first draw callback, or until drawing
  2324. // is complete when `!this.renderingQueue`, to prevent black flickering.
  2325. canvas.setAttribute('hidden', 'hidden');
  2326. var isCanvasHidden = true;
  2327. canvasWrapper.appendChild(canvas);
  2328. if (this.annotationLayer && this.annotationLayer.div) {
  2329. // annotationLayer needs to stay on top
  2330. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  2331. } else {
  2332. div.appendChild(canvasWrapper);
  2333. }
  2334. this.canvas = canvas;
  2335. canvas.mozOpaque = true;
  2336. var ctx = canvas.getContext('2d', {alpha: false});
  2337. var outputScale = getOutputScale(ctx);
  2338. this.outputScale = outputScale;
  2339. if (pdfjsLib.PDFJS.useOnlyCssZoom) {
  2340. var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
  2341. // Use a scale that will make the canvas be the original intended size
  2342. // of the page.
  2343. outputScale.sx *= actualSizeViewport.width / viewport.width;
  2344. outputScale.sy *= actualSizeViewport.height / viewport.height;
  2345. outputScale.scaled = true;
  2346. }
  2347. if (pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2348. var pixelsInViewport = viewport.width * viewport.height;
  2349. var maxScale =
  2350. Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
  2351. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  2352. outputScale.sx = maxScale;
  2353. outputScale.sy = maxScale;
  2354. outputScale.scaled = true;
  2355. this.hasRestrictedScaling = true;
  2356. } else {
  2357. this.hasRestrictedScaling = false;
  2358. }
  2359. }
  2360. var sfx = approximateFraction(outputScale.sx);
  2361. var sfy = approximateFraction(outputScale.sy);
  2362. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  2363. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  2364. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  2365. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  2366. // Add the viewport so it's known what it was originally drawn with.
  2367. canvas._viewport = viewport;
  2368. var textLayerDiv = null;
  2369. var textLayer = null;
  2370. if (this.textLayerFactory) {
  2371. textLayerDiv = document.createElement('div');
  2372. textLayerDiv.className = 'textLayer';
  2373. textLayerDiv.style.width = canvasWrapper.style.width;
  2374. textLayerDiv.style.height = canvasWrapper.style.height;
  2375. if (this.annotationLayer && this.annotationLayer.div) {
  2376. // annotationLayer needs to stay on top
  2377. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  2378. } else {
  2379. div.appendChild(textLayerDiv);
  2380. }
  2381. textLayer = this.textLayerFactory.
  2382. createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport,
  2383. this.enhanceTextSelection);
  2384. }
  2385. this.textLayer = textLayer;
  2386. var resolveRenderPromise, rejectRenderPromise;
  2387. var promise = new Promise(function (resolve, reject) {
  2388. resolveRenderPromise = resolve;
  2389. rejectRenderPromise = reject;
  2390. });
  2391. // Rendering area
  2392. var self = this;
  2393. function pageViewDrawCallback(error) {
  2394. // The renderTask may have been replaced by a new one, so only remove
  2395. // the reference to the renderTask if it matches the one that is
  2396. // triggering this callback.
  2397. if (renderTask === self.renderTask) {
  2398. self.renderTask = null;
  2399. }
  2400. if (error === 'cancelled') {
  2401. rejectRenderPromise(error);
  2402. return;
  2403. }
  2404. self.renderingState = RenderingStates.FINISHED;
  2405. if (isCanvasHidden) {
  2406. self.canvas.removeAttribute('hidden');
  2407. isCanvasHidden = false;
  2408. }
  2409. if (self.loadingIconDiv) {
  2410. div.removeChild(self.loadingIconDiv);
  2411. delete self.loadingIconDiv;
  2412. }
  2413. if (self.zoomLayer) {
  2414. // Zeroing the width and height causes Firefox to release graphics
  2415. // resources immediately, which can greatly reduce memory consumption.
  2416. var zoomLayerCanvas = self.zoomLayer.firstChild;
  2417. zoomLayerCanvas.width = 0;
  2418. zoomLayerCanvas.height = 0;
  2419. if (div.contains(self.zoomLayer)) {
  2420. // Prevent "Node was not found" errors if the `zoomLayer` was
  2421. // already removed. This may occur intermittently if the scale
  2422. // changes many times in very quick succession.
  2423. div.removeChild(self.zoomLayer);
  2424. }
  2425. self.zoomLayer = null;
  2426. }
  2427. self.error = error;
  2428. self.stats = pdfPage.stats;
  2429. if (self.onAfterDraw) {
  2430. self.onAfterDraw();
  2431. }
  2432. self.eventBus.dispatch('pagerendered', {
  2433. source: self,
  2434. pageNumber: self.id,
  2435. cssTransform: false,
  2436. });
  2437. if (!error) {
  2438. resolveRenderPromise(undefined);
  2439. } else {
  2440. rejectRenderPromise(error);
  2441. }
  2442. }
  2443. var renderContinueCallback = null;
  2444. if (this.renderingQueue) {
  2445. renderContinueCallback = function renderContinueCallback(cont) {
  2446. if (!self.renderingQueue.isHighestPriority(self)) {
  2447. self.renderingState = RenderingStates.PAUSED;
  2448. self.resume = function resumeCallback() {
  2449. self.renderingState = RenderingStates.RUNNING;
  2450. cont();
  2451. };
  2452. return;
  2453. }
  2454. if (isCanvasHidden) {
  2455. self.canvas.removeAttribute('hidden');
  2456. isCanvasHidden = false;
  2457. }
  2458. cont();
  2459. };
  2460. }
  2461. var transform = !outputScale.scaled ? null :
  2462. [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  2463. var renderContext = {
  2464. canvasContext: ctx,
  2465. transform: transform,
  2466. viewport: this.viewport,
  2467. renderInteractiveForms: this.renderInteractiveForms,
  2468. // intent: 'default', // === 'display'
  2469. };
  2470. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  2471. renderTask.onContinue = renderContinueCallback;
  2472. this.renderTask.promise.then(
  2473. function pdfPageRenderCallback() {
  2474. pageViewDrawCallback(null);
  2475. if (textLayer) {
  2476. self.pdfPage.getTextContent({
  2477. normalizeWhitespace: true,
  2478. }).then(function textContentResolved(textContent) {
  2479. textLayer.setTextContent(textContent);
  2480. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2481. });
  2482. }
  2483. },
  2484. function pdfPageRenderError(error) {
  2485. pageViewDrawCallback(error);
  2486. }
  2487. );
  2488. if (this.annotationLayerFactory) {
  2489. if (!this.annotationLayer) {
  2490. this.annotationLayer = this.annotationLayerFactory.
  2491. createAnnotationLayerBuilder(div, this.pdfPage,
  2492. this.renderInteractiveForms);
  2493. }
  2494. this.annotationLayer.render(this.viewport, 'display');
  2495. }
  2496. div.setAttribute('data-loaded', true);
  2497. if (self.onBeforeDraw) {
  2498. self.onBeforeDraw();
  2499. }
  2500. return promise;
  2501. },
  2502. };
  2503. return PDFPageView;
  2504. })();
  2505. exports.PDFPageView = PDFPageView;
  2506. }));
  2507. (function (root, factory) {
  2508. {
  2509. factory((root.pdfjsWebTextLayerBuilder = {}), root.pdfjsWebDOMEvents,
  2510. root.pdfjsWebPDFJS);
  2511. }
  2512. }(this, function (exports, domEvents, pdfjsLib) {
  2513. var EXPAND_DIVS_TIMEOUT = 300; // ms
  2514. /**
  2515. * @typedef {Object} TextLayerBuilderOptions
  2516. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  2517. * @property {EventBus} eventBus - The application event bus.
  2518. * @property {number} pageIndex - The page index.
  2519. * @property {PageViewport} viewport - The viewport of the text layer.
  2520. * @property {PDFFindController} findController
  2521. * @property {boolean} enhanceTextSelection - Option to turn on improved
  2522. * text selection.
  2523. */
  2524. /**
  2525. * TextLayerBuilder provides text-selection functionality for the PDF.
  2526. * It does this by creating overlay divs over the PDF text. These divs
  2527. * contain text that matches the PDF text they are overlaying. This object
  2528. * also provides a way to highlight text that is being searched for.
  2529. * @class
  2530. */
  2531. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  2532. function TextLayerBuilder(options) {
  2533. this.textLayerDiv = options.textLayerDiv;
  2534. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2535. this.renderingDone = false;
  2536. this.divContentDone = false;
  2537. this.pageIdx = options.pageIndex;
  2538. this.pageNumber = this.pageIdx + 1;
  2539. this.matches = [];
  2540. this.viewport = options.viewport;
  2541. this.textDivs = [];
  2542. this.findController = options.findController || null;
  2543. this.textLayerRenderTask = null;
  2544. this.enhanceTextSelection = options.enhanceTextSelection;
  2545. this._bindMouse();
  2546. }
  2547. TextLayerBuilder.prototype = {
  2548. _finishRendering: function TextLayerBuilder_finishRendering() {
  2549. this.renderingDone = true;
  2550. if (!this.enhanceTextSelection) {
  2551. var endOfContent = document.createElement('div');
  2552. endOfContent.className = 'endOfContent';
  2553. this.textLayerDiv.appendChild(endOfContent);
  2554. }
  2555. this.eventBus.dispatch('textlayerrendered', {
  2556. source: this,
  2557. pageNumber: this.pageNumber
  2558. });
  2559. },
  2560. /**
  2561. * Renders the text layer.
  2562. * @param {number} timeout (optional) if specified, the rendering waits
  2563. * for specified amount of ms.
  2564. */
  2565. render: function TextLayerBuilder_render(timeout) {
  2566. if (!this.divContentDone || this.renderingDone) {
  2567. return;
  2568. }
  2569. if (this.textLayerRenderTask) {
  2570. this.textLayerRenderTask.cancel();
  2571. this.textLayerRenderTask = null;
  2572. }
  2573. this.textDivs = [];
  2574. var textLayerFrag = document.createDocumentFragment();
  2575. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  2576. textContent: this.textContent,
  2577. container: textLayerFrag,
  2578. viewport: this.viewport,
  2579. textDivs: this.textDivs,
  2580. timeout: timeout,
  2581. enhanceTextSelection: this.enhanceTextSelection,
  2582. });
  2583. this.textLayerRenderTask.promise.then(function () {
  2584. this.textLayerDiv.appendChild(textLayerFrag);
  2585. this._finishRendering();
  2586. this.updateMatches();
  2587. }.bind(this), function (reason) {
  2588. // canceled or failed to render text layer -- skipping errors
  2589. });
  2590. },
  2591. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  2592. if (this.textLayerRenderTask) {
  2593. this.textLayerRenderTask.cancel();
  2594. this.textLayerRenderTask = null;
  2595. }
  2596. this.textContent = textContent;
  2597. this.divContentDone = true;
  2598. },
  2599. convertMatches: function TextLayerBuilder_convertMatches(matches,
  2600. matchesLength) {
  2601. var i = 0;
  2602. var iIndex = 0;
  2603. var bidiTexts = this.textContent.items;
  2604. var end = bidiTexts.length - 1;
  2605. var queryLen = (this.findController === null ?
  2606. 0 : this.findController.state.query.length);
  2607. var ret = [];
  2608. if (!matches) {
  2609. return ret;
  2610. }
  2611. for (var m = 0, len = matches.length; m < len; m++) {
  2612. // Calculate the start position.
  2613. var matchIdx = matches[m];
  2614. // Loop over the divIdxs.
  2615. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  2616. iIndex += bidiTexts[i].str.length;
  2617. i++;
  2618. }
  2619. if (i === bidiTexts.length) {
  2620. console.error('Could not find a matching mapping');
  2621. }
  2622. var match = {
  2623. begin: {
  2624. divIdx: i,
  2625. offset: matchIdx - iIndex
  2626. }
  2627. };
  2628. // Calculate the end position.
  2629. if (matchesLength) { // multiterm search
  2630. matchIdx += matchesLength[m];
  2631. } else { // phrase search
  2632. matchIdx += queryLen;
  2633. }
  2634. // Somewhat the same array as above, but use > instead of >= to get
  2635. // the end position right.
  2636. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  2637. iIndex += bidiTexts[i].str.length;
  2638. i++;
  2639. }
  2640. match.end = {
  2641. divIdx: i,
  2642. offset: matchIdx - iIndex
  2643. };
  2644. ret.push(match);
  2645. }
  2646. return ret;
  2647. },
  2648. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  2649. // Early exit if there is nothing to render.
  2650. if (matches.length === 0) {
  2651. return;
  2652. }
  2653. var bidiTexts = this.textContent.items;
  2654. var textDivs = this.textDivs;
  2655. var prevEnd = null;
  2656. var pageIdx = this.pageIdx;
  2657. var isSelectedPage = (this.findController === null ?
  2658. false : (pageIdx === this.findController.selected.pageIdx));
  2659. var selectedMatchIdx = (this.findController === null ?
  2660. -1 : this.findController.selected.matchIdx);
  2661. var highlightAll = (this.findController === null ?
  2662. false : this.findController.state.highlightAll);
  2663. var infinity = {
  2664. divIdx: -1,
  2665. offset: undefined
  2666. };
  2667. function beginText(begin, className) {
  2668. var divIdx = begin.divIdx;
  2669. textDivs[divIdx].textContent = '';
  2670. appendTextToDiv(divIdx, 0, begin.offset, className);
  2671. }
  2672. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  2673. var div = textDivs[divIdx];
  2674. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  2675. var node = document.createTextNode(content);
  2676. if (className) {
  2677. var span = document.createElement('span');
  2678. span.className = className;
  2679. span.appendChild(node);
  2680. div.appendChild(span);
  2681. return;
  2682. }
  2683. div.appendChild(node);
  2684. }
  2685. var i0 = selectedMatchIdx, i1 = i0 + 1;
  2686. if (highlightAll) {
  2687. i0 = 0;
  2688. i1 = matches.length;
  2689. } else if (!isSelectedPage) {
  2690. // Not highlighting all and this isn't the selected page, so do nothing.
  2691. return;
  2692. }
  2693. for (var i = i0; i < i1; i++) {
  2694. var match = matches[i];
  2695. var begin = match.begin;
  2696. var end = match.end;
  2697. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  2698. var highlightSuffix = (isSelected ? ' selected' : '');
  2699. if (this.findController) {
  2700. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  2701. begin.divIdx);
  2702. }
  2703. // Match inside new div.
  2704. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  2705. // If there was a previous div, then add the text at the end.
  2706. if (prevEnd !== null) {
  2707. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2708. }
  2709. // Clear the divs and set the content until the starting point.
  2710. beginText(begin);
  2711. } else {
  2712. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  2713. }
  2714. if (begin.divIdx === end.divIdx) {
  2715. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  2716. 'highlight' + highlightSuffix);
  2717. } else {
  2718. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  2719. 'highlight begin' + highlightSuffix);
  2720. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  2721. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  2722. }
  2723. beginText(end, 'highlight end' + highlightSuffix);
  2724. }
  2725. prevEnd = end;
  2726. }
  2727. if (prevEnd) {
  2728. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2729. }
  2730. },
  2731. updateMatches: function TextLayerBuilder_updateMatches() {
  2732. // Only show matches when all rendering is done.
  2733. if (!this.renderingDone) {
  2734. return;
  2735. }
  2736. // Clear all matches.
  2737. var matches = this.matches;
  2738. var textDivs = this.textDivs;
  2739. var bidiTexts = this.textContent.items;
  2740. var clearedUntilDivIdx = -1;
  2741. // Clear all current matches.
  2742. for (var i = 0, len = matches.length; i < len; i++) {
  2743. var match = matches[i];
  2744. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  2745. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  2746. var div = textDivs[n];
  2747. div.textContent = bidiTexts[n].str;
  2748. div.className = '';
  2749. }
  2750. clearedUntilDivIdx = match.end.divIdx + 1;
  2751. }
  2752. if (this.findController === null || !this.findController.active) {
  2753. return;
  2754. }
  2755. // Convert the matches on the page controller into the match format
  2756. // used for the textLayer.
  2757. var pageMatches, pageMatchesLength;
  2758. if (this.findController !== null) {
  2759. pageMatches = this.findController.pageMatches[this.pageIdx] || null;
  2760. pageMatchesLength = (this.findController.pageMatchesLength) ?
  2761. this.findController.pageMatchesLength[this.pageIdx] || null : null;
  2762. }
  2763. this.matches = this.convertMatches(pageMatches, pageMatchesLength);
  2764. this.renderMatches(this.matches);
  2765. },
  2766. /**
  2767. * Fixes text selection: adds additional div where mouse was clicked.
  2768. * This reduces flickering of the content if mouse slowly dragged down/up.
  2769. * @private
  2770. */
  2771. _bindMouse: function TextLayerBuilder_bindMouse() {
  2772. var div = this.textLayerDiv;
  2773. var self = this;
  2774. var expandDivsTimer = null;
  2775. div.addEventListener('mousedown', function (e) {
  2776. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  2777. self.textLayerRenderTask.expandTextDivs(true);
  2778. if (expandDivsTimer) {
  2779. clearTimeout(expandDivsTimer);
  2780. expandDivsTimer = null;
  2781. }
  2782. return;
  2783. }
  2784. var end = div.querySelector('.endOfContent');
  2785. if (!end) {
  2786. return;
  2787. }
  2788. // On non-Firefox browsers, the selection will feel better if the height
  2789. // of the endOfContent div will be adjusted to start at mouse click
  2790. // location -- this will avoid flickering when selections moves up.
  2791. // However it does not work when selection started on empty space.
  2792. var adjustTop = e.target !== div;
  2793. adjustTop = adjustTop && window.getComputedStyle(end).
  2794. getPropertyValue('-moz-user-select') !== 'none';
  2795. if (adjustTop) {
  2796. var divBounds = div.getBoundingClientRect();
  2797. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  2798. end.style.top = (r * 100).toFixed(2) + '%';
  2799. }
  2800. end.classList.add('active');
  2801. });
  2802. div.addEventListener('mouseup', function (e) {
  2803. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  2804. expandDivsTimer = setTimeout(function() {
  2805. self.textLayerRenderTask.expandTextDivs(false);
  2806. expandDivsTimer = null;
  2807. }, EXPAND_DIVS_TIMEOUT);
  2808. return;
  2809. }
  2810. var end = div.querySelector('.endOfContent');
  2811. if (!end) {
  2812. return;
  2813. }
  2814. end.style.top = '';
  2815. end.classList.remove('active');
  2816. });
  2817. },
  2818. };
  2819. return TextLayerBuilder;
  2820. })();
  2821. /**
  2822. * @constructor
  2823. * @implements IPDFTextLayerFactory
  2824. */
  2825. function DefaultTextLayerFactory() {}
  2826. DefaultTextLayerFactory.prototype = {
  2827. /**
  2828. * @param {HTMLDivElement} textLayerDiv
  2829. * @param {number} pageIndex
  2830. * @param {PageViewport} viewport
  2831. * @param {boolean} enhanceTextSelection
  2832. * @returns {TextLayerBuilder}
  2833. */
  2834. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport,
  2835. enhanceTextSelection) {
  2836. return new TextLayerBuilder({
  2837. textLayerDiv: textLayerDiv,
  2838. pageIndex: pageIndex,
  2839. viewport: viewport,
  2840. enhanceTextSelection: enhanceTextSelection
  2841. });
  2842. }
  2843. };
  2844. exports.TextLayerBuilder = TextLayerBuilder;
  2845. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2846. }));
  2847. (function (root, factory) {
  2848. {
  2849. factory((root.pdfjsWebAnnotationLayerBuilder = {}), root.pdfjsWebUIUtils,
  2850. root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS);
  2851. }
  2852. }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) {
  2853. var mozL10n = uiUtils.mozL10n;
  2854. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2855. /**
  2856. * @typedef {Object} AnnotationLayerBuilderOptions
  2857. * @property {HTMLDivElement} pageDiv
  2858. * @property {PDFPage} pdfPage
  2859. * @property {boolean} renderInteractiveForms
  2860. * @property {IPDFLinkService} linkService
  2861. * @property {DownloadManager} downloadManager
  2862. */
  2863. /**
  2864. * @class
  2865. */
  2866. var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
  2867. /**
  2868. * @param {AnnotationLayerBuilderOptions} options
  2869. * @constructs AnnotationLayerBuilder
  2870. */
  2871. function AnnotationLayerBuilder(options) {
  2872. this.pageDiv = options.pageDiv;
  2873. this.pdfPage = options.pdfPage;
  2874. this.renderInteractiveForms = options.renderInteractiveForms;
  2875. this.linkService = options.linkService;
  2876. this.downloadManager = options.downloadManager;
  2877. this.div = null;
  2878. }
  2879. AnnotationLayerBuilder.prototype =
  2880. /** @lends AnnotationLayerBuilder.prototype */ {
  2881. /**
  2882. * @param {PageViewport} viewport
  2883. * @param {string} intent (default value is 'display')
  2884. */
  2885. render: function AnnotationLayerBuilder_render(viewport, intent) {
  2886. var self = this;
  2887. var parameters = {
  2888. intent: (intent === undefined ? 'display' : intent),
  2889. };
  2890. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  2891. viewport = viewport.clone({ dontFlip: true });
  2892. parameters = {
  2893. viewport: viewport,
  2894. div: self.div,
  2895. annotations: annotations,
  2896. page: self.pdfPage,
  2897. renderInteractiveForms: self.renderInteractiveForms,
  2898. linkService: self.linkService,
  2899. downloadManager: self.downloadManager,
  2900. };
  2901. if (self.div) {
  2902. // If an annotationLayer already exists, refresh its children's
  2903. // transformation matrices.
  2904. pdfjsLib.AnnotationLayer.update(parameters);
  2905. } else {
  2906. // Create an annotation layer div and render the annotations
  2907. // if there is at least one annotation.
  2908. if (annotations.length === 0) {
  2909. return;
  2910. }
  2911. self.div = document.createElement('div');
  2912. self.div.className = 'annotationLayer';
  2913. self.pageDiv.appendChild(self.div);
  2914. parameters.div = self.div;
  2915. pdfjsLib.AnnotationLayer.render(parameters);
  2916. if (typeof mozL10n !== 'undefined') {
  2917. mozL10n.translate(self.div);
  2918. }
  2919. }
  2920. });
  2921. },
  2922. hide: function AnnotationLayerBuilder_hide() {
  2923. if (!this.div) {
  2924. return;
  2925. }
  2926. this.div.setAttribute('hidden', 'true');
  2927. }
  2928. };
  2929. return AnnotationLayerBuilder;
  2930. })();
  2931. /**
  2932. * @constructor
  2933. * @implements IPDFAnnotationLayerFactory
  2934. */
  2935. function DefaultAnnotationLayerFactory() {}
  2936. DefaultAnnotationLayerFactory.prototype = {
  2937. /**
  2938. * @param {HTMLDivElement} pageDiv
  2939. * @param {PDFPage} pdfPage
  2940. * @param {boolean} renderInteractiveForms
  2941. * @returns {AnnotationLayerBuilder}
  2942. */
  2943. createAnnotationLayerBuilder: function (pageDiv, pdfPage,
  2944. renderInteractiveForms) {
  2945. return new AnnotationLayerBuilder({
  2946. pageDiv: pageDiv,
  2947. pdfPage: pdfPage,
  2948. renderInteractiveForms: renderInteractiveForms,
  2949. linkService: new SimpleLinkService(),
  2950. });
  2951. }
  2952. };
  2953. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  2954. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  2955. }));
  2956. (function (root, factory) {
  2957. {
  2958. factory((root.pdfjsWebPDFViewer = {}), root.pdfjsWebUIUtils,
  2959. root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue,
  2960. root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder,
  2961. root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2962. }
  2963. }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue,
  2964. textLayerBuilder, annotationLayerBuilder, pdfLinkService,
  2965. domEvents, pdfjsLib) {
  2966. var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE;
  2967. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  2968. var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING;
  2969. var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE;
  2970. var CSS_UNITS = uiUtils.CSS_UNITS;
  2971. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2972. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  2973. var scrollIntoView = uiUtils.scrollIntoView;
  2974. var watchScroll = uiUtils.watchScroll;
  2975. var getVisibleElements = uiUtils.getVisibleElements;
  2976. var PDFPageView = pdfPageView.PDFPageView;
  2977. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2978. var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue;
  2979. var TextLayerBuilder = textLayerBuilder.TextLayerBuilder;
  2980. var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder;
  2981. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2982. var PresentationModeState = {
  2983. UNKNOWN: 0,
  2984. NORMAL: 1,
  2985. CHANGING: 2,
  2986. FULLSCREEN: 3,
  2987. };
  2988. var DEFAULT_CACHE_SIZE = 10;
  2989. /**
  2990. * @typedef {Object} PDFViewerOptions
  2991. * @property {HTMLDivElement} container - The container for the viewer element.
  2992. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  2993. * @property {EventBus} eventBus - The application event bus.
  2994. * @property {IPDFLinkService} linkService - The navigation/linking service.
  2995. * @property {DownloadManager} downloadManager - (optional) The download
  2996. * manager component.
  2997. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  2998. * queue object.
  2999. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  3000. * around the pages. The default is false.
  3001. * @property {boolean} enhanceTextSelection - (optional) Enables the improved
  3002. * text selection behaviour. The default is `false`.
  3003. * @property {boolean} renderInteractiveForms - (optional) Enables rendering of
  3004. * interactive form elements. The default is `false`.
  3005. */
  3006. /**
  3007. * Simple viewer control to display PDF content/pages.
  3008. * @class
  3009. * @implements {IRenderableView}
  3010. */
  3011. var PDFViewer = (function pdfViewer() {
  3012. function PDFPageViewBuffer(size) {
  3013. var data = [];
  3014. this.push = function cachePush(view) {
  3015. var i = data.indexOf(view);
  3016. if (i >= 0) {
  3017. data.splice(i, 1);
  3018. }
  3019. data.push(view);
  3020. if (data.length > size) {
  3021. data.shift().destroy();
  3022. }
  3023. };
  3024. this.resize = function (newSize) {
  3025. size = newSize;
  3026. while (data.length > size) {
  3027. data.shift().destroy();
  3028. }
  3029. };
  3030. }
  3031. function isSameScale(oldScale, newScale) {
  3032. if (newScale === oldScale) {
  3033. return true;
  3034. }
  3035. if (Math.abs(newScale - oldScale) < 1e-15) {
  3036. // Prevent unnecessary re-rendering of all pages when the scale
  3037. // changes only because of limited numerical precision.
  3038. return true;
  3039. }
  3040. return false;
  3041. }
  3042. /**
  3043. * @constructs PDFViewer
  3044. * @param {PDFViewerOptions} options
  3045. */
  3046. function PDFViewer(options) {
  3047. this.container = options.container;
  3048. this.viewer = options.viewer || options.container.firstElementChild;
  3049. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3050. this.linkService = options.linkService || new SimpleLinkService();
  3051. this.downloadManager = options.downloadManager || null;
  3052. this.removePageBorders = options.removePageBorders || false;
  3053. this.enhanceTextSelection = options.enhanceTextSelection || false;
  3054. this.renderInteractiveForms = options.renderInteractiveForms || false;
  3055. this.defaultRenderingQueue = !options.renderingQueue;
  3056. if (this.defaultRenderingQueue) {
  3057. // Custom rendering queue is not specified, using default one
  3058. this.renderingQueue = new PDFRenderingQueue();
  3059. this.renderingQueue.setViewer(this);
  3060. } else {
  3061. this.renderingQueue = options.renderingQueue;
  3062. }
  3063. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  3064. this.presentationModeState = PresentationModeState.UNKNOWN;
  3065. this._resetView();
  3066. if (this.removePageBorders) {
  3067. this.viewer.classList.add('removePageBorders');
  3068. }
  3069. }
  3070. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  3071. get pagesCount() {
  3072. return this._pages.length;
  3073. },
  3074. getPageView: function (index) {
  3075. return this._pages[index];
  3076. },
  3077. /**
  3078. * @returns {boolean} true if all {PDFPageView} objects are initialized.
  3079. */
  3080. get pageViewsReady() {
  3081. return this._pageViewsReady;
  3082. },
  3083. /**
  3084. * @returns {number}
  3085. */
  3086. get currentPageNumber() {
  3087. return this._currentPageNumber;
  3088. },
  3089. /**
  3090. * @param {number} val - The page number.
  3091. */
  3092. set currentPageNumber(val) {
  3093. if ((val | 0) !== val) { // Ensure that `val` is an integer.
  3094. throw new Error('Invalid page number.');
  3095. }
  3096. if (!this.pdfDocument) {
  3097. this._currentPageNumber = val;
  3098. return;
  3099. }
  3100. // The intent can be to just reset a scroll position and/or scale.
  3101. this._setCurrentPageNumber(val, /* resetCurrentPageView = */ true);
  3102. },
  3103. /**
  3104. * @private
  3105. */
  3106. _setCurrentPageNumber:
  3107. function PDFViewer_setCurrentPageNumber(val, resetCurrentPageView) {
  3108. if (this._currentPageNumber === val) {
  3109. if (resetCurrentPageView) {
  3110. this._resetCurrentPageView();
  3111. }
  3112. return;
  3113. }
  3114. if (!(0 < val && val <= this.pagesCount)) {
  3115. console.error('PDFViewer_setCurrentPageNumber: "' + val +
  3116. '" is out of bounds.');
  3117. return;
  3118. }
  3119. var arg = {
  3120. source: this,
  3121. pageNumber: val,
  3122. };
  3123. this._currentPageNumber = val;
  3124. this.eventBus.dispatch('pagechanging', arg);
  3125. this.eventBus.dispatch('pagechange', arg);
  3126. if (resetCurrentPageView) {
  3127. this._resetCurrentPageView();
  3128. }
  3129. },
  3130. /**
  3131. * @returns {number}
  3132. */
  3133. get currentScale() {
  3134. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  3135. DEFAULT_SCALE;
  3136. },
  3137. /**
  3138. * @param {number} val - Scale of the pages in percents.
  3139. */
  3140. set currentScale(val) {
  3141. if (isNaN(val)) {
  3142. throw new Error('Invalid numeric scale');
  3143. }
  3144. if (!this.pdfDocument) {
  3145. this._currentScale = val;
  3146. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  3147. return;
  3148. }
  3149. this._setScale(val, false);
  3150. },
  3151. /**
  3152. * @returns {string}
  3153. */
  3154. get currentScaleValue() {
  3155. return this._currentScaleValue;
  3156. },
  3157. /**
  3158. * @param val - The scale of the pages (in percent or predefined value).
  3159. */
  3160. set currentScaleValue(val) {
  3161. if (!this.pdfDocument) {
  3162. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  3163. this._currentScaleValue = val.toString();
  3164. return;
  3165. }
  3166. this._setScale(val, false);
  3167. },
  3168. /**
  3169. * @returns {number}
  3170. */
  3171. get pagesRotation() {
  3172. return this._pagesRotation;
  3173. },
  3174. /**
  3175. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  3176. */
  3177. set pagesRotation(rotation) {
  3178. if (!(typeof rotation === 'number' && rotation % 90 === 0)) {
  3179. throw new Error('Invalid pages rotation angle.');
  3180. }
  3181. this._pagesRotation = rotation;
  3182. if (!this.pdfDocument) {
  3183. return;
  3184. }
  3185. for (var i = 0, l = this._pages.length; i < l; i++) {
  3186. var pageView = this._pages[i];
  3187. pageView.update(pageView.scale, rotation);
  3188. }
  3189. this._setScale(this._currentScaleValue, true);
  3190. if (this.defaultRenderingQueue) {
  3191. this.update();
  3192. }
  3193. },
  3194. /**
  3195. * @param pdfDocument {PDFDocument}
  3196. */
  3197. setDocument: function (pdfDocument) {
  3198. if (this.pdfDocument) {
  3199. this._resetView();
  3200. }
  3201. this.pdfDocument = pdfDocument;
  3202. if (!pdfDocument) {
  3203. return;
  3204. }
  3205. var pagesCount = pdfDocument.numPages;
  3206. var self = this;
  3207. var resolvePagesPromise;
  3208. var pagesPromise = new Promise(function (resolve) {
  3209. resolvePagesPromise = resolve;
  3210. });
  3211. this.pagesPromise = pagesPromise;
  3212. pagesPromise.then(function () {
  3213. self._pageViewsReady = true;
  3214. self.eventBus.dispatch('pagesloaded', {
  3215. source: self,
  3216. pagesCount: pagesCount
  3217. });
  3218. });
  3219. var isOnePageRenderedResolved = false;
  3220. var resolveOnePageRendered = null;
  3221. var onePageRendered = new Promise(function (resolve) {
  3222. resolveOnePageRendered = resolve;
  3223. });
  3224. this.onePageRendered = onePageRendered;
  3225. var bindOnAfterAndBeforeDraw = function (pageView) {
  3226. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  3227. // Add the page to the buffer at the start of drawing. That way it can
  3228. // be evicted from the buffer and destroyed even if we pause its
  3229. // rendering.
  3230. self._buffer.push(this);
  3231. };
  3232. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  3233. if (!isOnePageRenderedResolved) {
  3234. isOnePageRenderedResolved = true;
  3235. resolveOnePageRendered();
  3236. }
  3237. };
  3238. };
  3239. var firstPagePromise = pdfDocument.getPage(1);
  3240. this.firstPagePromise = firstPagePromise;
  3241. // Fetch a single page so we can get a viewport that will be the default
  3242. // viewport for all pages
  3243. return firstPagePromise.then(function(pdfPage) {
  3244. var scale = this.currentScale;
  3245. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  3246. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3247. var textLayerFactory = null;
  3248. if (!pdfjsLib.PDFJS.disableTextLayer) {
  3249. textLayerFactory = this;
  3250. }
  3251. var pageView = new PDFPageView({
  3252. container: this.viewer,
  3253. eventBus: this.eventBus,
  3254. id: pageNum,
  3255. scale: scale,
  3256. defaultViewport: viewport.clone(),
  3257. renderingQueue: this.renderingQueue,
  3258. textLayerFactory: textLayerFactory,
  3259. annotationLayerFactory: this,
  3260. enhanceTextSelection: this.enhanceTextSelection,
  3261. renderInteractiveForms: this.renderInteractiveForms,
  3262. });
  3263. bindOnAfterAndBeforeDraw(pageView);
  3264. this._pages.push(pageView);
  3265. }
  3266. var linkService = this.linkService;
  3267. // Fetch all the pages since the viewport is needed before printing
  3268. // starts to create the correct size canvas. Wait until one page is
  3269. // rendered so we don't tie up too many resources early on.
  3270. onePageRendered.then(function () {
  3271. if (!pdfjsLib.PDFJS.disableAutoFetch) {
  3272. var getPagesLeft = pagesCount;
  3273. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3274. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  3275. var pageView = self._pages[pageNum - 1];
  3276. if (!pageView.pdfPage) {
  3277. pageView.setPdfPage(pdfPage);
  3278. }
  3279. linkService.cachePageRef(pageNum, pdfPage.ref);
  3280. getPagesLeft--;
  3281. if (!getPagesLeft) {
  3282. resolvePagesPromise();
  3283. }
  3284. }.bind(null, pageNum));
  3285. }
  3286. } else {
  3287. // XXX: Printing is semi-broken with auto fetch disabled.
  3288. resolvePagesPromise();
  3289. }
  3290. });
  3291. self.eventBus.dispatch('pagesinit', {source: self});
  3292. if (this.defaultRenderingQueue) {
  3293. this.update();
  3294. }
  3295. if (this.findController) {
  3296. this.findController.resolveFirstPage();
  3297. }
  3298. }.bind(this));
  3299. },
  3300. _resetView: function () {
  3301. this._pages = [];
  3302. this._currentPageNumber = 1;
  3303. this._currentScale = UNKNOWN_SCALE;
  3304. this._currentScaleValue = null;
  3305. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  3306. this._location = null;
  3307. this._pagesRotation = 0;
  3308. this._pagesRequests = [];
  3309. this._pageViewsReady = false;
  3310. var container = this.viewer;
  3311. while (container.hasChildNodes()) {
  3312. container.removeChild(container.lastChild);
  3313. }
  3314. },
  3315. _scrollUpdate: function PDFViewer_scrollUpdate() {
  3316. if (this.pagesCount === 0) {
  3317. return;
  3318. }
  3319. this.update();
  3320. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3321. this._pages[i].updatePosition();
  3322. }
  3323. },
  3324. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  3325. newScale, newValue, preset) {
  3326. var arg = {
  3327. source: this,
  3328. scale: newScale,
  3329. presetValue: preset ? newValue : undefined
  3330. };
  3331. this.eventBus.dispatch('scalechanging', arg);
  3332. this.eventBus.dispatch('scalechange', arg);
  3333. },
  3334. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  3335. newScale, newValue, noScroll, preset) {
  3336. this._currentScaleValue = newValue.toString();
  3337. if (isSameScale(this._currentScale, newScale)) {
  3338. if (preset) {
  3339. this._setScaleDispatchEvent(newScale, newValue, true);
  3340. }
  3341. return;
  3342. }
  3343. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3344. this._pages[i].update(newScale);
  3345. }
  3346. this._currentScale = newScale;
  3347. if (!noScroll) {
  3348. var page = this._currentPageNumber, dest;
  3349. if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom &&
  3350. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  3351. page = this._location.pageNumber;
  3352. dest = [null, { name: 'XYZ' }, this._location.left,
  3353. this._location.top, null];
  3354. }
  3355. this.scrollPageIntoView({
  3356. pageNumber: page,
  3357. destArray: dest,
  3358. allowNegativeOffset: true,
  3359. });
  3360. }
  3361. this._setScaleDispatchEvent(newScale, newValue, preset);
  3362. if (this.defaultRenderingQueue) {
  3363. this.update();
  3364. }
  3365. },
  3366. _setScale: function PDFViewer_setScale(value, noScroll) {
  3367. var scale = parseFloat(value);
  3368. if (scale > 0) {
  3369. this._setScaleUpdatePages(scale, value, noScroll, false);
  3370. } else {
  3371. var currentPage = this._pages[this._currentPageNumber - 1];
  3372. if (!currentPage) {
  3373. return;
  3374. }
  3375. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  3376. 0 : SCROLLBAR_PADDING;
  3377. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  3378. 0 : VERTICAL_PADDING;
  3379. var pageWidthScale = (this.container.clientWidth - hPadding) /
  3380. currentPage.width * currentPage.scale;
  3381. var pageHeightScale = (this.container.clientHeight - vPadding) /
  3382. currentPage.height * currentPage.scale;
  3383. switch (value) {
  3384. case 'page-actual':
  3385. scale = 1;
  3386. break;
  3387. case 'page-width':
  3388. scale = pageWidthScale;
  3389. break;
  3390. case 'page-height':
  3391. scale = pageHeightScale;
  3392. break;
  3393. case 'page-fit':
  3394. scale = Math.min(pageWidthScale, pageHeightScale);
  3395. break;
  3396. case 'auto':
  3397. var isLandscape = (currentPage.width > currentPage.height);
  3398. // For pages in landscape mode, fit the page height to the viewer
  3399. // *unless* the page would thus become too wide to fit horizontally.
  3400. var horizontalScale = isLandscape ?
  3401. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  3402. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  3403. break;
  3404. default:
  3405. console.error('PDFViewer_setScale: "' + value +
  3406. '" is an unknown zoom value.');
  3407. return;
  3408. }
  3409. this._setScaleUpdatePages(scale, value, noScroll, true);
  3410. }
  3411. },
  3412. /**
  3413. * Refreshes page view: scrolls to the current page and updates the scale.
  3414. * @private
  3415. */
  3416. _resetCurrentPageView: function () {
  3417. if (this.isInPresentationMode) {
  3418. // Fixes the case when PDF has different page sizes.
  3419. this._setScale(this._currentScaleValue, true);
  3420. }
  3421. var pageView = this._pages[this._currentPageNumber - 1];
  3422. scrollIntoView(pageView.div);
  3423. },
  3424. /**
  3425. * @typedef ScrollPageIntoViewParameters
  3426. * @param {number} pageNumber - The page number.
  3427. * @param {Array} destArray - (optional) The original PDF destination array,
  3428. * in the format: <page-ref> </XYZ|/FitXXX> <args..>
  3429. * @param {boolean} allowNegativeOffset - (optional) Allow negative page
  3430. * offsets. The default value is `false`.
  3431. */
  3432. /**
  3433. * Scrolls page into view.
  3434. * @param {ScrollPageIntoViewParameters} params
  3435. */
  3436. scrollPageIntoView: function PDFViewer_scrollPageIntoView(params) {
  3437. if (!this.pdfDocument) {
  3438. return;
  3439. }
  3440. if (arguments.length > 1 || typeof params === 'number') {
  3441. console.warn('Call of scrollPageIntoView() with obsolete signature.');
  3442. var paramObj = {};
  3443. if (typeof params === 'number') {
  3444. paramObj.pageNumber = params; // pageNumber argument was found.
  3445. }
  3446. if (arguments[1] instanceof Array) {
  3447. paramObj.destArray = arguments[1]; // destArray argument was found.
  3448. }
  3449. params = paramObj;
  3450. }
  3451. var pageNumber = params.pageNumber || 0;
  3452. var dest = params.destArray || null;
  3453. var allowNegativeOffset = params.allowNegativeOffset || false;
  3454. if (this.isInPresentationMode || !dest) {
  3455. this._setCurrentPageNumber(pageNumber, /* resetCurrentPageView */ true);
  3456. return;
  3457. }
  3458. var pageView = this._pages[pageNumber - 1];
  3459. if (!pageView) {
  3460. console.error('PDFViewer_scrollPageIntoView: ' +
  3461. 'Invalid "pageNumber" parameter.');
  3462. return;
  3463. }
  3464. var x = 0, y = 0;
  3465. var width = 0, height = 0, widthScale, heightScale;
  3466. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  3467. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  3468. pageView.scale / CSS_UNITS;
  3469. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  3470. pageView.scale / CSS_UNITS;
  3471. var scale = 0;
  3472. switch (dest[1].name) {
  3473. case 'XYZ':
  3474. x = dest[2];
  3475. y = dest[3];
  3476. scale = dest[4];
  3477. // If x and/or y coordinates are not supplied, default to
  3478. // _top_ left of the page (not the obvious bottom left,
  3479. // since aligning the bottom of the intended page with the
  3480. // top of the window is rarely helpful).
  3481. x = x !== null ? x : 0;
  3482. y = y !== null ? y : pageHeight;
  3483. break;
  3484. case 'Fit':
  3485. case 'FitB':
  3486. scale = 'page-fit';
  3487. break;
  3488. case 'FitH':
  3489. case 'FitBH':
  3490. y = dest[2];
  3491. scale = 'page-width';
  3492. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  3493. // parameter should maintain the position relative to the new page.
  3494. if (y === null && this._location) {
  3495. x = this._location.left;
  3496. y = this._location.top;
  3497. }
  3498. break;
  3499. case 'FitV':
  3500. case 'FitBV':
  3501. x = dest[2];
  3502. width = pageWidth;
  3503. height = pageHeight;
  3504. scale = 'page-height';
  3505. break;
  3506. case 'FitR':
  3507. x = dest[2];
  3508. y = dest[3];
  3509. width = dest[4] - x;
  3510. height = dest[5] - y;
  3511. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3512. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  3513. widthScale = (this.container.clientWidth - hPadding) /
  3514. width / CSS_UNITS;
  3515. heightScale = (this.container.clientHeight - vPadding) /
  3516. height / CSS_UNITS;
  3517. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  3518. break;
  3519. default:
  3520. console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name +
  3521. '\' is not a valid destination type.');
  3522. return;
  3523. }
  3524. if (scale && scale !== this._currentScale) {
  3525. this.currentScaleValue = scale;
  3526. } else if (this._currentScale === UNKNOWN_SCALE) {
  3527. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  3528. }
  3529. if (scale === 'page-fit' && !dest[4]) {
  3530. scrollIntoView(pageView.div);
  3531. return;
  3532. }
  3533. var boundingRect = [
  3534. pageView.viewport.convertToViewportPoint(x, y),
  3535. pageView.viewport.convertToViewportPoint(x + width, y + height)
  3536. ];
  3537. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  3538. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  3539. if (!allowNegativeOffset) {
  3540. // Some bad PDF generators will create destinations with e.g. top values
  3541. // that exceeds the page height. Ensure that offsets are not negative,
  3542. // to prevent a previous page from becoming visible (fixes bug 874482).
  3543. left = Math.max(left, 0);
  3544. top = Math.max(top, 0);
  3545. }
  3546. scrollIntoView(pageView.div, { left: left, top: top });
  3547. },
  3548. _updateLocation: function (firstPage) {
  3549. var currentScale = this._currentScale;
  3550. var currentScaleValue = this._currentScaleValue;
  3551. var normalizedScaleValue =
  3552. parseFloat(currentScaleValue) === currentScale ?
  3553. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  3554. var pageNumber = firstPage.id;
  3555. var pdfOpenParams = '#page=' + pageNumber;
  3556. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  3557. var currentPageView = this._pages[pageNumber - 1];
  3558. var container = this.container;
  3559. var topLeft = currentPageView.getPagePoint(
  3560. (container.scrollLeft - firstPage.x),
  3561. (container.scrollTop - firstPage.y));
  3562. var intLeft = Math.round(topLeft[0]);
  3563. var intTop = Math.round(topLeft[1]);
  3564. pdfOpenParams += ',' + intLeft + ',' + intTop;
  3565. this._location = {
  3566. pageNumber: pageNumber,
  3567. scale: normalizedScaleValue,
  3568. top: intTop,
  3569. left: intLeft,
  3570. pdfOpenParams: pdfOpenParams
  3571. };
  3572. },
  3573. update: function PDFViewer_update() {
  3574. var visible = this._getVisiblePages();
  3575. var visiblePages = visible.views;
  3576. if (visiblePages.length === 0) {
  3577. return;
  3578. }
  3579. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  3580. 2 * visiblePages.length + 1);
  3581. this._buffer.resize(suggestedCacheSize);
  3582. this.renderingQueue.renderHighestPriority(visible);
  3583. var currentId = this._currentPageNumber;
  3584. var firstPage = visible.first;
  3585. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  3586. i < ii; ++i) {
  3587. var page = visiblePages[i];
  3588. if (page.percent < 100) {
  3589. break;
  3590. }
  3591. if (page.id === currentId) {
  3592. stillFullyVisible = true;
  3593. break;
  3594. }
  3595. }
  3596. if (!stillFullyVisible) {
  3597. currentId = visiblePages[0].id;
  3598. }
  3599. if (!this.isInPresentationMode) {
  3600. this._setCurrentPageNumber(currentId);
  3601. }
  3602. this._updateLocation(firstPage);
  3603. this.eventBus.dispatch('updateviewarea', {
  3604. source: this,
  3605. location: this._location
  3606. });
  3607. },
  3608. containsElement: function (element) {
  3609. return this.container.contains(element);
  3610. },
  3611. focus: function () {
  3612. this.container.focus();
  3613. },
  3614. get isInPresentationMode() {
  3615. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  3616. },
  3617. get isChangingPresentationMode() {
  3618. return this.presentationModeState === PresentationModeState.CHANGING;
  3619. },
  3620. get isHorizontalScrollbarEnabled() {
  3621. return (this.isInPresentationMode ?
  3622. false : (this.container.scrollWidth > this.container.clientWidth));
  3623. },
  3624. _getVisiblePages: function () {
  3625. if (!this.isInPresentationMode) {
  3626. return getVisibleElements(this.container, this._pages, true);
  3627. } else {
  3628. // The algorithm in getVisibleElements doesn't work in all browsers and
  3629. // configurations when presentation mode is active.
  3630. var visible = [];
  3631. var currentPage = this._pages[this._currentPageNumber - 1];
  3632. visible.push({ id: currentPage.id, view: currentPage });
  3633. return { first: currentPage, last: currentPage, views: visible };
  3634. }
  3635. },
  3636. cleanup: function () {
  3637. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3638. if (this._pages[i] &&
  3639. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  3640. this._pages[i].reset();
  3641. }
  3642. }
  3643. },
  3644. /**
  3645. * @param {PDFPageView} pageView
  3646. * @returns {PDFPage}
  3647. * @private
  3648. */
  3649. _ensurePdfPageLoaded: function (pageView) {
  3650. if (pageView.pdfPage) {
  3651. return Promise.resolve(pageView.pdfPage);
  3652. }
  3653. var pageNumber = pageView.id;
  3654. if (this._pagesRequests[pageNumber]) {
  3655. return this._pagesRequests[pageNumber];
  3656. }
  3657. var promise = this.pdfDocument.getPage(pageNumber).then(
  3658. function (pdfPage) {
  3659. pageView.setPdfPage(pdfPage);
  3660. this._pagesRequests[pageNumber] = null;
  3661. return pdfPage;
  3662. }.bind(this));
  3663. this._pagesRequests[pageNumber] = promise;
  3664. return promise;
  3665. },
  3666. forceRendering: function (currentlyVisiblePages) {
  3667. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  3668. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  3669. this._pages,
  3670. this.scroll.down);
  3671. if (pageView) {
  3672. this._ensurePdfPageLoaded(pageView).then(function () {
  3673. this.renderingQueue.renderView(pageView);
  3674. }.bind(this));
  3675. return true;
  3676. }
  3677. return false;
  3678. },
  3679. getPageTextContent: function (pageIndex) {
  3680. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  3681. return page.getTextContent({
  3682. normalizeWhitespace: true,
  3683. });
  3684. });
  3685. },
  3686. /**
  3687. * @param {HTMLDivElement} textLayerDiv
  3688. * @param {number} pageIndex
  3689. * @param {PageViewport} viewport
  3690. * @returns {TextLayerBuilder}
  3691. */
  3692. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport,
  3693. enhanceTextSelection) {
  3694. return new TextLayerBuilder({
  3695. textLayerDiv: textLayerDiv,
  3696. eventBus: this.eventBus,
  3697. pageIndex: pageIndex,
  3698. viewport: viewport,
  3699. findController: this.isInPresentationMode ? null : this.findController,
  3700. enhanceTextSelection: this.isInPresentationMode ? false :
  3701. enhanceTextSelection,
  3702. });
  3703. },
  3704. /**
  3705. * @param {HTMLDivElement} pageDiv
  3706. * @param {PDFPage} pdfPage
  3707. * @param {boolean} renderInteractiveForms
  3708. * @returns {AnnotationLayerBuilder}
  3709. */
  3710. createAnnotationLayerBuilder: function (pageDiv, pdfPage,
  3711. renderInteractiveForms) {
  3712. return new AnnotationLayerBuilder({
  3713. pageDiv: pageDiv,
  3714. pdfPage: pdfPage,
  3715. renderInteractiveForms: renderInteractiveForms,
  3716. linkService: this.linkService,
  3717. downloadManager: this.downloadManager
  3718. });
  3719. },
  3720. setFindController: function (findController) {
  3721. this.findController = findController;
  3722. },
  3723. /**
  3724. * Returns sizes of the pages.
  3725. * @returns {Array} Array of objects with width/height fields.
  3726. */
  3727. getPagesOverview: function () {
  3728. return this._pages.map(function (pageView) {
  3729. var viewport = pageView.pdfPage.getViewport(1);
  3730. return {width: viewport.width, height: viewport.height};
  3731. });
  3732. },
  3733. };
  3734. return PDFViewer;
  3735. })();
  3736. exports.PresentationModeState = PresentationModeState;
  3737. exports.PDFViewer = PDFViewer;
  3738. }));
  3739. }).call(pdfViewerLibs);
  3740. var PDFJS = pdfjsLib.PDFJS;
  3741. PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer;
  3742. PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView;
  3743. PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService;
  3744. PDFJS.TextLayerBuilder =
  3745. pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder;
  3746. PDFJS.DefaultTextLayerFactory =
  3747. pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory;
  3748. PDFJS.AnnotationLayerBuilder =
  3749. pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder;
  3750. PDFJS.DefaultAnnotationLayerFactory =
  3751. pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory;
  3752. PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory;
  3753. PDFJS.PDFFindController =
  3754. pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController;
  3755. PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus;
  3756. PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager;
  3757. PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar;
  3758. exports.PDFJS = PDFJS;
  3759. }));