pdf_viewer.js 134 KB

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