pdf_viewer.js 124 KB

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