2
0

pdf_viewer.js 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134
  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. /* globals PDFJS, PDFViewer, PDFPageView, TextLayerBuilder, PDFLinkService,
  17. DefaultTextLayerFactory, AnnotationLayerBuilder, PDFHistory,
  18. DefaultAnnotationLayerFactory, DownloadManager, ProgressBar */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. (function pdfViewerWrapper() {
  24. 'use strict';
  25. var CSS_UNITS = 96.0 / 72.0;
  26. var DEFAULT_SCALE_VALUE = 'auto';
  27. var DEFAULT_SCALE = 1.0;
  28. var UNKNOWN_SCALE = 0;
  29. var MAX_AUTO_SCALE = 1.25;
  30. var SCROLLBAR_PADDING = 40;
  31. var VERTICAL_PADDING = 5;
  32. var mozL10n = document.mozL10n || document.webL10n;
  33. /**
  34. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  35. * @return {Object} The object with horizontal (sx) and vertical (sy)
  36. scales. The scaled property is set to false if scaling is
  37. not required, true otherwise.
  38. */
  39. function getOutputScale(ctx) {
  40. var devicePixelRatio = window.devicePixelRatio || 1;
  41. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  42. ctx.mozBackingStorePixelRatio ||
  43. ctx.msBackingStorePixelRatio ||
  44. ctx.oBackingStorePixelRatio ||
  45. ctx.backingStorePixelRatio || 1;
  46. var pixelRatio = devicePixelRatio / backingStoreRatio;
  47. return {
  48. sx: pixelRatio,
  49. sy: pixelRatio,
  50. scaled: pixelRatio !== 1
  51. };
  52. }
  53. /**
  54. * Scrolls specified element into view of its parent.
  55. * @param {Object} element - The element to be visible.
  56. * @param {Object} spot - An object with optional top and left properties,
  57. * specifying the offset from the top left edge.
  58. * @param {boolean} skipOverflowHiddenElements - Ignore elements that have
  59. * the CSS rule `overflow: hidden;` set. The default is false.
  60. */
  61. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  62. // Assuming offsetParent is available (it's not available when viewer is in
  63. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  64. // producing the error. See also animationStartedClosure.
  65. var parent = element.offsetParent;
  66. if (!parent) {
  67. console.error('offsetParent is not set -- cannot scroll');
  68. return;
  69. }
  70. var checkOverflow = skipOverflowHiddenElements || false;
  71. var offsetY = element.offsetTop + element.clientTop;
  72. var offsetX = element.offsetLeft + element.clientLeft;
  73. while (parent.clientHeight === parent.scrollHeight ||
  74. (checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
  75. if (parent.dataset._scaleY) {
  76. offsetY /= parent.dataset._scaleY;
  77. offsetX /= parent.dataset._scaleX;
  78. }
  79. offsetY += parent.offsetTop;
  80. offsetX += parent.offsetLeft;
  81. parent = parent.offsetParent;
  82. if (!parent) {
  83. return; // no need to scroll
  84. }
  85. }
  86. if (spot) {
  87. if (spot.top !== undefined) {
  88. offsetY += spot.top;
  89. }
  90. if (spot.left !== undefined) {
  91. offsetX += spot.left;
  92. parent.scrollLeft = offsetX;
  93. }
  94. }
  95. parent.scrollTop = offsetY;
  96. }
  97. /**
  98. * Helper function to start monitoring the scroll event and converting them into
  99. * PDF.js friendly one: with scroll debounce and scroll direction.
  100. */
  101. function watchScroll(viewAreaElement, callback) {
  102. var debounceScroll = function debounceScroll(evt) {
  103. if (rAF) {
  104. return;
  105. }
  106. // schedule an invocation of scroll for next animation frame.
  107. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  108. rAF = null;
  109. var currentY = viewAreaElement.scrollTop;
  110. var lastY = state.lastY;
  111. if (currentY !== lastY) {
  112. state.down = currentY > lastY;
  113. }
  114. state.lastY = currentY;
  115. callback(state);
  116. });
  117. };
  118. var state = {
  119. down: true,
  120. lastY: viewAreaElement.scrollTop,
  121. _eventHandler: debounceScroll
  122. };
  123. var rAF = null;
  124. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  125. return state;
  126. }
  127. /**
  128. * Helper function to parse query string (e.g. ?param1=value&parm2=...).
  129. */
  130. function parseQueryString(query) {
  131. var parts = query.split('&');
  132. var params = {};
  133. for (var i = 0, ii = parts.length; i < ii; ++i) {
  134. var param = parts[i].split('=');
  135. var key = param[0].toLowerCase();
  136. var value = param.length > 1 ? param[1] : null;
  137. params[decodeURIComponent(key)] = decodeURIComponent(value);
  138. }
  139. return params;
  140. }
  141. /**
  142. * Use binary search to find the index of the first item in a given array which
  143. * passes a given condition. The items are expected to be sorted in the sense
  144. * that if the condition is true for one item in the array, then it is also true
  145. * for all following items.
  146. *
  147. * @returns {Number} Index of the first array element to pass the test,
  148. * or |items.length| if no such element exists.
  149. */
  150. function binarySearchFirstItem(items, condition) {
  151. var minIndex = 0;
  152. var maxIndex = items.length - 1;
  153. if (items.length === 0 || !condition(items[maxIndex])) {
  154. return items.length;
  155. }
  156. if (condition(items[minIndex])) {
  157. return minIndex;
  158. }
  159. while (minIndex < maxIndex) {
  160. var currentIndex = (minIndex + maxIndex) >> 1;
  161. var currentItem = items[currentIndex];
  162. if (condition(currentItem)) {
  163. maxIndex = currentIndex;
  164. } else {
  165. minIndex = currentIndex + 1;
  166. }
  167. }
  168. return minIndex; /* === maxIndex */
  169. }
  170. /**
  171. * Approximates float number as a fraction using Farey sequence (max order
  172. * of 8).
  173. * @param {number} x - Positive float number.
  174. * @returns {Array} Estimated fraction: the first array item is a numerator,
  175. * the second one is a denominator.
  176. */
  177. function approximateFraction(x) {
  178. // Fast paths for int numbers or their inversions.
  179. if (Math.floor(x) === x) {
  180. return [x, 1];
  181. }
  182. var xinv = 1 / x;
  183. var limit = 8;
  184. if (xinv > limit) {
  185. return [1, limit];
  186. } else if (Math.floor(xinv) === xinv) {
  187. return [1, xinv];
  188. }
  189. var x_ = x > 1 ? xinv : x;
  190. // a/b and c/d are neighbours in Farey sequence.
  191. var a = 0, b = 1, c = 1, d = 1;
  192. // Limiting search to order 8.
  193. while (true) {
  194. // Generating next term in sequence (order of q).
  195. var p = a + c, q = b + d;
  196. if (q > limit) {
  197. break;
  198. }
  199. if (x_ <= p / q) {
  200. c = p; d = q;
  201. } else {
  202. a = p; b = q;
  203. }
  204. }
  205. // Select closest of the neighbours to x.
  206. if (x_ - a / b < c / d - x_) {
  207. return x_ === x ? [a, b] : [b, a];
  208. } else {
  209. return x_ === x ? [c, d] : [d, c];
  210. }
  211. }
  212. function roundToDivide(x, div) {
  213. var r = x % div;
  214. return r === 0 ? x : Math.round(x - r + div);
  215. }
  216. /**
  217. * Generic helper to find out what elements are visible within a scroll pane.
  218. */
  219. function getVisibleElements(scrollEl, views, sortByVisibility) {
  220. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  221. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  222. function isElementBottomBelowViewTop(view) {
  223. var element = view.div;
  224. var elementBottom =
  225. element.offsetTop + element.clientTop + element.clientHeight;
  226. return elementBottom > top;
  227. }
  228. var visible = [], view, element;
  229. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  230. var currentWidth, viewWidth;
  231. var firstVisibleElementInd = (views.length === 0) ? 0 :
  232. binarySearchFirstItem(views, isElementBottomBelowViewTop);
  233. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  234. view = views[i];
  235. element = view.div;
  236. currentHeight = element.offsetTop + element.clientTop;
  237. viewHeight = element.clientHeight;
  238. if (currentHeight > bottom) {
  239. break;
  240. }
  241. currentWidth = element.offsetLeft + element.clientLeft;
  242. viewWidth = element.clientWidth;
  243. if (currentWidth + viewWidth < left || currentWidth > right) {
  244. continue;
  245. }
  246. hiddenHeight = Math.max(0, top - currentHeight) +
  247. Math.max(0, currentHeight + viewHeight - bottom);
  248. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  249. visible.push({
  250. id: view.id,
  251. x: currentWidth,
  252. y: currentHeight,
  253. view: view,
  254. percent: percentHeight
  255. });
  256. }
  257. var first = visible[0];
  258. var last = visible[visible.length - 1];
  259. if (sortByVisibility) {
  260. visible.sort(function(a, b) {
  261. var pc = a.percent - b.percent;
  262. if (Math.abs(pc) > 0.001) {
  263. return -pc;
  264. }
  265. return a.id - b.id; // ensure stability
  266. });
  267. }
  268. return {first: first, last: last, views: visible};
  269. }
  270. /**
  271. * Event handler to suppress context menu.
  272. */
  273. function noContextMenuHandler(e) {
  274. e.preventDefault();
  275. }
  276. /**
  277. * Returns the filename or guessed filename from the url (see issue 3455).
  278. * url {String} The original PDF location.
  279. * @return {String} Guessed PDF file name.
  280. */
  281. function getPDFFileNameFromURL(url) {
  282. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  283. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  284. // Pattern to get last matching NAME.pdf
  285. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  286. var splitURI = reURI.exec(url);
  287. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  288. reFilename.exec(splitURI[2]) ||
  289. reFilename.exec(splitURI[3]);
  290. if (suggestedFilename) {
  291. suggestedFilename = suggestedFilename[0];
  292. if (suggestedFilename.indexOf('%') !== -1) {
  293. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  294. try {
  295. suggestedFilename =
  296. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  297. } catch(e) { // Possible (extremely rare) errors:
  298. // URIError "Malformed URI", e.g. for "%AA.pdf"
  299. // TypeError "null has no properties", e.g. for "%2F.pdf"
  300. }
  301. }
  302. }
  303. return suggestedFilename || 'document.pdf';
  304. }
  305. var ProgressBar = (function ProgressBarClosure() {
  306. function clamp(v, min, max) {
  307. return Math.min(Math.max(v, min), max);
  308. }
  309. function ProgressBar(id, opts) {
  310. this.visible = true;
  311. // Fetch the sub-elements for later.
  312. this.div = document.querySelector(id + ' .progress');
  313. // Get the loading bar element, so it can be resized to fit the viewer.
  314. this.bar = this.div.parentNode;
  315. // Get options, with sensible defaults.
  316. this.height = opts.height || 100;
  317. this.width = opts.width || 100;
  318. this.units = opts.units || '%';
  319. // Initialize heights.
  320. this.div.style.height = this.height + this.units;
  321. this.percent = 0;
  322. }
  323. ProgressBar.prototype = {
  324. updateBar: function ProgressBar_updateBar() {
  325. if (this._indeterminate) {
  326. this.div.classList.add('indeterminate');
  327. this.div.style.width = this.width + this.units;
  328. return;
  329. }
  330. this.div.classList.remove('indeterminate');
  331. var progressSize = this.width * this._percent / 100;
  332. this.div.style.width = progressSize + this.units;
  333. },
  334. get percent() {
  335. return this._percent;
  336. },
  337. set percent(val) {
  338. this._indeterminate = isNaN(val);
  339. this._percent = clamp(val, 0, 100);
  340. this.updateBar();
  341. },
  342. setWidth: function ProgressBar_setWidth(viewer) {
  343. if (viewer) {
  344. var container = viewer.parentNode;
  345. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  346. if (scrollbarWidth > 0) {
  347. this.bar.setAttribute('style', 'width: calc(100% - ' +
  348. scrollbarWidth + 'px);');
  349. }
  350. }
  351. },
  352. hide: function ProgressBar_hide() {
  353. if (!this.visible) {
  354. return;
  355. }
  356. this.visible = false;
  357. this.bar.classList.add('hidden');
  358. document.body.classList.remove('loadingInProgress');
  359. },
  360. show: function ProgressBar_show() {
  361. if (this.visible) {
  362. return;
  363. }
  364. this.visible = true;
  365. document.body.classList.add('loadingInProgress');
  366. this.bar.classList.remove('hidden');
  367. }
  368. };
  369. return ProgressBar;
  370. })();
  371. /**
  372. * Performs navigation functions inside PDF, such as opening specified page,
  373. * or destination.
  374. * @class
  375. * @implements {IPDFLinkService}
  376. */
  377. var PDFLinkService = (function () {
  378. /**
  379. * @constructs PDFLinkService
  380. */
  381. function PDFLinkService() {
  382. this.baseUrl = null;
  383. this.pdfDocument = null;
  384. this.pdfViewer = null;
  385. this.pdfHistory = null;
  386. this._pagesRefCache = null;
  387. }
  388. PDFLinkService.prototype = {
  389. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  390. this.baseUrl = baseUrl;
  391. this.pdfDocument = pdfDocument;
  392. this._pagesRefCache = Object.create(null);
  393. },
  394. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  395. this.pdfViewer = pdfViewer;
  396. },
  397. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  398. this.pdfHistory = pdfHistory;
  399. },
  400. /**
  401. * @returns {number}
  402. */
  403. get pagesCount() {
  404. return this.pdfDocument.numPages;
  405. },
  406. /**
  407. * @returns {number}
  408. */
  409. get page() {
  410. return this.pdfViewer.currentPageNumber;
  411. },
  412. /**
  413. * @param {number} value
  414. */
  415. set page(value) {
  416. this.pdfViewer.currentPageNumber = value;
  417. },
  418. /**
  419. * @param dest - The PDF destination object.
  420. */
  421. navigateTo: function PDFLinkService_navigateTo(dest) {
  422. var destString = '';
  423. var self = this;
  424. var goToDestination = function(destRef) {
  425. // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
  426. var pageNumber = destRef instanceof Object ?
  427. self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  428. (destRef + 1);
  429. if (pageNumber) {
  430. if (pageNumber > self.pagesCount) {
  431. pageNumber = self.pagesCount;
  432. }
  433. self.pdfViewer.scrollPageIntoView(pageNumber, dest);
  434. if (self.pdfHistory) {
  435. // Update the browsing history.
  436. self.pdfHistory.push({
  437. dest: dest,
  438. hash: destString,
  439. page: pageNumber
  440. });
  441. }
  442. } else {
  443. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  444. var pageNum = pageIndex + 1;
  445. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  446. self._pagesRefCache[cacheKey] = pageNum;
  447. goToDestination(destRef);
  448. });
  449. }
  450. };
  451. var destinationPromise;
  452. if (typeof dest === 'string') {
  453. destString = dest;
  454. destinationPromise = this.pdfDocument.getDestination(dest);
  455. } else {
  456. destinationPromise = Promise.resolve(dest);
  457. }
  458. destinationPromise.then(function(destination) {
  459. dest = destination;
  460. if (!(destination instanceof Array)) {
  461. return; // invalid destination
  462. }
  463. goToDestination(destination[0]);
  464. });
  465. },
  466. /**
  467. * @param dest - The PDF destination object.
  468. * @returns {string} The hyperlink to the PDF object.
  469. */
  470. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  471. if (typeof dest === 'string') {
  472. return this.getAnchorUrl('#' + escape(dest));
  473. }
  474. if (dest instanceof Array) {
  475. var destRef = dest[0]; // see navigateTo method for dest format
  476. var pageNumber = destRef instanceof Object ?
  477. this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  478. (destRef + 1);
  479. if (pageNumber) {
  480. var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
  481. var destKind = dest[1];
  482. if (typeof destKind === 'object' && 'name' in destKind &&
  483. destKind.name === 'XYZ') {
  484. var scale = (dest[4] || this.pdfViewer.currentScaleValue);
  485. var scaleNumber = parseFloat(scale);
  486. if (scaleNumber) {
  487. scale = scaleNumber * 100;
  488. }
  489. pdfOpenParams += '&zoom=' + scale;
  490. if (dest[2] || dest[3]) {
  491. pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
  492. }
  493. }
  494. return pdfOpenParams;
  495. }
  496. }
  497. return this.getAnchorUrl('');
  498. },
  499. /**
  500. * Prefix the full url on anchor links to make sure that links are resolved
  501. * relative to the current URL instead of the one defined in <base href>.
  502. * @param {String} anchor The anchor hash, including the #.
  503. * @returns {string} The hyperlink to the PDF object.
  504. */
  505. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  506. return (this.baseUrl || '') + anchor;
  507. },
  508. /**
  509. * @param {string} hash
  510. */
  511. setHash: function PDFLinkService_setHash(hash) {
  512. if (hash.indexOf('=') >= 0) {
  513. var params = parseQueryString(hash);
  514. // borrowing syntax from "Parameters for Opening PDF Files"
  515. if ('nameddest' in params) {
  516. if (this.pdfHistory) {
  517. this.pdfHistory.updateNextHashParam(params.nameddest);
  518. }
  519. this.navigateTo(params.nameddest);
  520. return;
  521. }
  522. var pageNumber, dest;
  523. if ('page' in params) {
  524. pageNumber = (params.page | 0) || 1;
  525. }
  526. if ('zoom' in params) {
  527. // Build the destination array.
  528. var zoomArgs = params.zoom.split(','); // scale,left,top
  529. var zoomArg = zoomArgs[0];
  530. var zoomArgNumber = parseFloat(zoomArg);
  531. if (zoomArg.indexOf('Fit') === -1) {
  532. // If the zoomArg is a number, it has to get divided by 100. If it's
  533. // a string, it should stay as it is.
  534. dest = [null, { name: 'XYZ' },
  535. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  536. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  537. (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
  538. } else {
  539. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  540. dest = [null, { name: zoomArg }];
  541. } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
  542. (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  543. dest = [null, { name: zoomArg },
  544. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
  545. } else if (zoomArg === 'FitR') {
  546. if (zoomArgs.length !== 5) {
  547. console.error('PDFLinkService_setHash: ' +
  548. 'Not enough parameters for \'FitR\'.');
  549. } else {
  550. dest = [null, { name: zoomArg },
  551. (zoomArgs[1] | 0), (zoomArgs[2] | 0),
  552. (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
  553. }
  554. } else {
  555. console.error('PDFLinkService_setHash: \'' + zoomArg +
  556. '\' is not a valid zoom value.');
  557. }
  558. }
  559. }
  560. if (dest) {
  561. this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
  562. } else if (pageNumber) {
  563. this.page = pageNumber; // simple page
  564. }
  565. if ('pagemode' in params) {
  566. var event = document.createEvent('CustomEvent');
  567. event.initCustomEvent('pagemode', true, true, {
  568. mode: params.pagemode,
  569. });
  570. this.pdfViewer.container.dispatchEvent(event);
  571. }
  572. } else if (/^\d+$/.test(hash)) { // page number
  573. this.page = hash;
  574. } else { // named destination
  575. if (this.pdfHistory) {
  576. this.pdfHistory.updateNextHashParam(unescape(hash));
  577. }
  578. this.navigateTo(unescape(hash));
  579. }
  580. },
  581. /**
  582. * @param {string} action
  583. */
  584. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  585. // See PDF reference, table 8.45 - Named action
  586. switch (action) {
  587. case 'GoBack':
  588. if (this.pdfHistory) {
  589. this.pdfHistory.back();
  590. }
  591. break;
  592. case 'GoForward':
  593. if (this.pdfHistory) {
  594. this.pdfHistory.forward();
  595. }
  596. break;
  597. case 'NextPage':
  598. this.page++;
  599. break;
  600. case 'PrevPage':
  601. this.page--;
  602. break;
  603. case 'LastPage':
  604. this.page = this.pagesCount;
  605. break;
  606. case 'FirstPage':
  607. this.page = 1;
  608. break;
  609. default:
  610. break; // No action according to spec
  611. }
  612. var event = document.createEvent('CustomEvent');
  613. event.initCustomEvent('namedaction', true, true, {
  614. action: action
  615. });
  616. this.pdfViewer.container.dispatchEvent(event);
  617. },
  618. /**
  619. * @param {number} pageNum - page number.
  620. * @param {Object} pageRef - reference to the page.
  621. */
  622. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  623. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  624. this._pagesRefCache[refStr] = pageNum;
  625. }
  626. };
  627. return PDFLinkService;
  628. })();
  629. var PresentationModeState = {
  630. UNKNOWN: 0,
  631. NORMAL: 1,
  632. CHANGING: 2,
  633. FULLSCREEN: 3,
  634. };
  635. var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
  636. var DEFAULT_CACHE_SIZE = 10;
  637. var CLEANUP_TIMEOUT = 30000;
  638. var RenderingStates = {
  639. INITIAL: 0,
  640. RUNNING: 1,
  641. PAUSED: 2,
  642. FINISHED: 3
  643. };
  644. /**
  645. * Controls rendering of the views for pages and thumbnails.
  646. * @class
  647. */
  648. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  649. /**
  650. * @constructs
  651. */
  652. function PDFRenderingQueue() {
  653. this.pdfViewer = null;
  654. this.pdfThumbnailViewer = null;
  655. this.onIdle = null;
  656. this.highestPriorityPage = null;
  657. this.idleTimeout = null;
  658. this.printing = false;
  659. this.isThumbnailViewEnabled = false;
  660. }
  661. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  662. /**
  663. * @param {PDFViewer} pdfViewer
  664. */
  665. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  666. this.pdfViewer = pdfViewer;
  667. },
  668. /**
  669. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  670. */
  671. setThumbnailViewer:
  672. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  673. this.pdfThumbnailViewer = pdfThumbnailViewer;
  674. },
  675. /**
  676. * @param {IRenderableView} view
  677. * @returns {boolean}
  678. */
  679. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  680. return this.highestPriorityPage === view.renderingId;
  681. },
  682. renderHighestPriority: function
  683. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  684. if (this.idleTimeout) {
  685. clearTimeout(this.idleTimeout);
  686. this.idleTimeout = null;
  687. }
  688. // Pages have a higher priority than thumbnails, so check them first.
  689. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  690. return;
  691. }
  692. // No pages needed rendering so check thumbnails.
  693. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  694. if (this.pdfThumbnailViewer.forceRendering()) {
  695. return;
  696. }
  697. }
  698. if (this.printing) {
  699. // If printing is currently ongoing do not reschedule cleanup.
  700. return;
  701. }
  702. if (this.onIdle) {
  703. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  704. }
  705. },
  706. getHighestPriority: function
  707. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  708. // The state has changed figure out which page has the highest priority to
  709. // render next (if any).
  710. // Priority:
  711. // 1 visible pages
  712. // 2 if last scrolled down page after the visible pages
  713. // 2 if last scrolled up page before the visible pages
  714. var visibleViews = visible.views;
  715. var numVisible = visibleViews.length;
  716. if (numVisible === 0) {
  717. return false;
  718. }
  719. for (var i = 0; i < numVisible; ++i) {
  720. var view = visibleViews[i].view;
  721. if (!this.isViewFinished(view)) {
  722. return view;
  723. }
  724. }
  725. // All the visible views have rendered, try to render next/previous pages.
  726. if (scrolledDown) {
  727. var nextPageIndex = visible.last.id;
  728. // ID's start at 1 so no need to add 1.
  729. if (views[nextPageIndex] &&
  730. !this.isViewFinished(views[nextPageIndex])) {
  731. return views[nextPageIndex];
  732. }
  733. } else {
  734. var previousPageIndex = visible.first.id - 2;
  735. if (views[previousPageIndex] &&
  736. !this.isViewFinished(views[previousPageIndex])) {
  737. return views[previousPageIndex];
  738. }
  739. }
  740. // Everything that needs to be rendered has been.
  741. return null;
  742. },
  743. /**
  744. * @param {IRenderableView} view
  745. * @returns {boolean}
  746. */
  747. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  748. return view.renderingState === RenderingStates.FINISHED;
  749. },
  750. /**
  751. * Render a page or thumbnail view. This calls the appropriate function
  752. * based on the views state. If the view is already rendered it will return
  753. * false.
  754. * @param {IRenderableView} view
  755. */
  756. renderView: function PDFRenderingQueue_renderView(view) {
  757. var state = view.renderingState;
  758. switch (state) {
  759. case RenderingStates.FINISHED:
  760. return false;
  761. case RenderingStates.PAUSED:
  762. this.highestPriorityPage = view.renderingId;
  763. view.resume();
  764. break;
  765. case RenderingStates.RUNNING:
  766. this.highestPriorityPage = view.renderingId;
  767. break;
  768. case RenderingStates.INITIAL:
  769. this.highestPriorityPage = view.renderingId;
  770. var continueRendering = function () {
  771. this.renderHighestPriority();
  772. }.bind(this);
  773. view.draw().then(continueRendering, continueRendering);
  774. break;
  775. }
  776. return true;
  777. },
  778. };
  779. return PDFRenderingQueue;
  780. })();
  781. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  782. /**
  783. * @typedef {Object} PDFPageViewOptions
  784. * @property {HTMLDivElement} container - The viewer element.
  785. * @property {number} id - The page unique ID (normally its number).
  786. * @property {number} scale - The page scale display.
  787. * @property {PageViewport} defaultViewport - The page viewport.
  788. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  789. * @property {IPDFTextLayerFactory} textLayerFactory
  790. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  791. */
  792. /**
  793. * @class
  794. * @implements {IRenderableView}
  795. */
  796. var PDFPageView = (function PDFPageViewClosure() {
  797. /**
  798. * @constructs PDFPageView
  799. * @param {PDFPageViewOptions} options
  800. */
  801. function PDFPageView(options) {
  802. var container = options.container;
  803. var id = options.id;
  804. var scale = options.scale;
  805. var defaultViewport = options.defaultViewport;
  806. var renderingQueue = options.renderingQueue;
  807. var textLayerFactory = options.textLayerFactory;
  808. var annotationLayerFactory = options.annotationLayerFactory;
  809. this.id = id;
  810. this.renderingId = 'page' + id;
  811. this.rotation = 0;
  812. this.scale = scale || DEFAULT_SCALE;
  813. this.viewport = defaultViewport;
  814. this.pdfPageRotate = defaultViewport.rotation;
  815. this.hasRestrictedScaling = false;
  816. this.renderingQueue = renderingQueue;
  817. this.textLayerFactory = textLayerFactory;
  818. this.annotationLayerFactory = annotationLayerFactory;
  819. this.renderingState = RenderingStates.INITIAL;
  820. this.resume = null;
  821. this.onBeforeDraw = null;
  822. this.onAfterDraw = null;
  823. this.textLayer = null;
  824. this.zoomLayer = null;
  825. this.annotationLayer = null;
  826. var div = document.createElement('div');
  827. div.id = 'pageContainer' + this.id;
  828. div.className = 'page';
  829. div.style.width = Math.floor(this.viewport.width) + 'px';
  830. div.style.height = Math.floor(this.viewport.height) + 'px';
  831. div.setAttribute('data-page-number', this.id);
  832. this.div = div;
  833. container.appendChild(div);
  834. }
  835. PDFPageView.prototype = {
  836. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  837. this.pdfPage = pdfPage;
  838. this.pdfPageRotate = pdfPage.rotate;
  839. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  840. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  841. totalRotation);
  842. this.stats = pdfPage.stats;
  843. this.reset();
  844. },
  845. destroy: function PDFPageView_destroy() {
  846. this.zoomLayer = null;
  847. this.reset();
  848. if (this.pdfPage) {
  849. this.pdfPage.cleanup();
  850. }
  851. },
  852. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  853. if (this.renderTask) {
  854. this.renderTask.cancel();
  855. }
  856. this.resume = null;
  857. this.renderingState = RenderingStates.INITIAL;
  858. var div = this.div;
  859. div.style.width = Math.floor(this.viewport.width) + 'px';
  860. div.style.height = Math.floor(this.viewport.height) + 'px';
  861. var childNodes = div.childNodes;
  862. var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
  863. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  864. this.annotationLayer.div) || null;
  865. for (var i = childNodes.length - 1; i >= 0; i--) {
  866. var node = childNodes[i];
  867. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  868. continue;
  869. }
  870. div.removeChild(node);
  871. }
  872. div.removeAttribute('data-loaded');
  873. if (currentAnnotationNode) {
  874. // Hide annotationLayer until all elements are resized
  875. // so they are not displayed on the already-resized page
  876. this.annotationLayer.hide();
  877. } else {
  878. this.annotationLayer = null;
  879. }
  880. if (this.canvas && !currentZoomLayerNode) {
  881. // Zeroing the width and height causes Firefox to release graphics
  882. // resources immediately, which can greatly reduce memory consumption.
  883. this.canvas.width = 0;
  884. this.canvas.height = 0;
  885. delete this.canvas;
  886. }
  887. this.loadingIconDiv = document.createElement('div');
  888. this.loadingIconDiv.className = 'loadingIcon';
  889. div.appendChild(this.loadingIconDiv);
  890. },
  891. update: function PDFPageView_update(scale, rotation) {
  892. this.scale = scale || this.scale;
  893. if (typeof rotation !== 'undefined') {
  894. this.rotation = rotation;
  895. }
  896. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  897. this.viewport = this.viewport.clone({
  898. scale: this.scale * CSS_UNITS,
  899. rotation: totalRotation
  900. });
  901. var isScalingRestricted = false;
  902. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  903. var outputScale = this.outputScale;
  904. var pixelsInViewport = this.viewport.width * this.viewport.height;
  905. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  906. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  907. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  908. PDFJS.maxCanvasPixels) {
  909. isScalingRestricted = true;
  910. }
  911. }
  912. if (this.canvas) {
  913. if (PDFJS.useOnlyCssZoom ||
  914. (this.hasRestrictedScaling && isScalingRestricted)) {
  915. this.cssTransform(this.canvas, true);
  916. var event = document.createEvent('CustomEvent');
  917. event.initCustomEvent('pagerendered', true, true, {
  918. pageNumber: this.id,
  919. cssTransform: true,
  920. });
  921. this.div.dispatchEvent(event);
  922. return;
  923. }
  924. if (!this.zoomLayer) {
  925. this.zoomLayer = this.canvas.parentNode;
  926. this.zoomLayer.style.position = 'absolute';
  927. }
  928. }
  929. if (this.zoomLayer) {
  930. this.cssTransform(this.zoomLayer.firstChild);
  931. }
  932. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
  933. },
  934. /**
  935. * Called when moved in the parent's container.
  936. */
  937. updatePosition: function PDFPageView_updatePosition() {
  938. if (this.textLayer) {
  939. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  940. }
  941. },
  942. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  943. var CustomStyle = PDFJS.CustomStyle;
  944. // Scale canvas, canvas wrapper, and page container.
  945. var width = this.viewport.width;
  946. var height = this.viewport.height;
  947. var div = this.div;
  948. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  949. Math.floor(width) + 'px';
  950. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  951. Math.floor(height) + 'px';
  952. // The canvas may have been originally rotated, rotate relative to that.
  953. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  954. var absRotation = Math.abs(relativeRotation);
  955. var scaleX = 1, scaleY = 1;
  956. if (absRotation === 90 || absRotation === 270) {
  957. // Scale x and y because of the rotation.
  958. scaleX = height / width;
  959. scaleY = width / height;
  960. }
  961. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  962. 'scale(' + scaleX + ',' + scaleY + ')';
  963. CustomStyle.setProp('transform', canvas, cssTransform);
  964. if (this.textLayer) {
  965. // Rotating the text layer is more complicated since the divs inside the
  966. // the text layer are rotated.
  967. // TODO: This could probably be simplified by drawing the text layer in
  968. // one orientation then rotating overall.
  969. var textLayerViewport = this.textLayer.viewport;
  970. var textRelativeRotation = this.viewport.rotation -
  971. textLayerViewport.rotation;
  972. var textAbsRotation = Math.abs(textRelativeRotation);
  973. var scale = width / textLayerViewport.width;
  974. if (textAbsRotation === 90 || textAbsRotation === 270) {
  975. scale = width / textLayerViewport.height;
  976. }
  977. var textLayerDiv = this.textLayer.textLayerDiv;
  978. var transX, transY;
  979. switch (textAbsRotation) {
  980. case 0:
  981. transX = transY = 0;
  982. break;
  983. case 90:
  984. transX = 0;
  985. transY = '-' + textLayerDiv.style.height;
  986. break;
  987. case 180:
  988. transX = '-' + textLayerDiv.style.width;
  989. transY = '-' + textLayerDiv.style.height;
  990. break;
  991. case 270:
  992. transX = '-' + textLayerDiv.style.width;
  993. transY = 0;
  994. break;
  995. default:
  996. console.error('Bad rotation value.');
  997. break;
  998. }
  999. CustomStyle.setProp('transform', textLayerDiv,
  1000. 'rotate(' + textAbsRotation + 'deg) ' +
  1001. 'scale(' + scale + ', ' + scale + ') ' +
  1002. 'translate(' + transX + ', ' + transY + ')');
  1003. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  1004. }
  1005. if (redrawAnnotations && this.annotationLayer) {
  1006. this.annotationLayer.render(this.viewport, 'display');
  1007. }
  1008. },
  1009. get width() {
  1010. return this.viewport.width;
  1011. },
  1012. get height() {
  1013. return this.viewport.height;
  1014. },
  1015. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  1016. return this.viewport.convertToPdfPoint(x, y);
  1017. },
  1018. draw: function PDFPageView_draw() {
  1019. if (this.renderingState !== RenderingStates.INITIAL) {
  1020. console.error('Must be in new state before drawing');
  1021. }
  1022. this.renderingState = RenderingStates.RUNNING;
  1023. var pdfPage = this.pdfPage;
  1024. var viewport = this.viewport;
  1025. var div = this.div;
  1026. // Wrap the canvas so if it has a css transform for highdpi the overflow
  1027. // will be hidden in FF.
  1028. var canvasWrapper = document.createElement('div');
  1029. canvasWrapper.style.width = div.style.width;
  1030. canvasWrapper.style.height = div.style.height;
  1031. canvasWrapper.classList.add('canvasWrapper');
  1032. var canvas = document.createElement('canvas');
  1033. canvas.id = 'page' + this.id;
  1034. // Keep the canvas hidden until the first draw callback, or until drawing
  1035. // is complete when `!this.renderingQueue`, to prevent black flickering.
  1036. canvas.setAttribute('hidden', 'hidden');
  1037. var isCanvasHidden = true;
  1038. canvasWrapper.appendChild(canvas);
  1039. if (this.annotationLayer && this.annotationLayer.div) {
  1040. // annotationLayer needs to stay on top
  1041. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  1042. } else {
  1043. div.appendChild(canvasWrapper);
  1044. }
  1045. this.canvas = canvas;
  1046. var ctx = canvas.getContext('2d', {alpha: false});
  1047. var outputScale = getOutputScale(ctx);
  1048. this.outputScale = outputScale;
  1049. if (PDFJS.useOnlyCssZoom) {
  1050. var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
  1051. // Use a scale that will make the canvas be the original intended size
  1052. // of the page.
  1053. outputScale.sx *= actualSizeViewport.width / viewport.width;
  1054. outputScale.sy *= actualSizeViewport.height / viewport.height;
  1055. outputScale.scaled = true;
  1056. }
  1057. if (PDFJS.maxCanvasPixels > 0) {
  1058. var pixelsInViewport = viewport.width * viewport.height;
  1059. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  1060. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  1061. outputScale.sx = maxScale;
  1062. outputScale.sy = maxScale;
  1063. outputScale.scaled = true;
  1064. this.hasRestrictedScaling = true;
  1065. } else {
  1066. this.hasRestrictedScaling = false;
  1067. }
  1068. }
  1069. var sfx = approximateFraction(outputScale.sx);
  1070. var sfy = approximateFraction(outputScale.sy);
  1071. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  1072. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  1073. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  1074. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  1075. // Add the viewport so it's known what it was originally drawn with.
  1076. canvas._viewport = viewport;
  1077. var textLayerDiv = null;
  1078. var textLayer = null;
  1079. if (this.textLayerFactory) {
  1080. textLayerDiv = document.createElement('div');
  1081. textLayerDiv.className = 'textLayer';
  1082. textLayerDiv.style.width = canvasWrapper.style.width;
  1083. textLayerDiv.style.height = canvasWrapper.style.height;
  1084. if (this.annotationLayer && this.annotationLayer.div) {
  1085. // annotationLayer needs to stay on top
  1086. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  1087. } else {
  1088. div.appendChild(textLayerDiv);
  1089. }
  1090. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  1091. this.id - 1,
  1092. this.viewport);
  1093. }
  1094. this.textLayer = textLayer;
  1095. var resolveRenderPromise, rejectRenderPromise;
  1096. var promise = new Promise(function (resolve, reject) {
  1097. resolveRenderPromise = resolve;
  1098. rejectRenderPromise = reject;
  1099. });
  1100. // Rendering area
  1101. var self = this;
  1102. function pageViewDrawCallback(error) {
  1103. // The renderTask may have been replaced by a new one, so only remove
  1104. // the reference to the renderTask if it matches the one that is
  1105. // triggering this callback.
  1106. if (renderTask === self.renderTask) {
  1107. self.renderTask = null;
  1108. }
  1109. if (error === 'cancelled') {
  1110. rejectRenderPromise(error);
  1111. return;
  1112. }
  1113. self.renderingState = RenderingStates.FINISHED;
  1114. if (isCanvasHidden) {
  1115. self.canvas.removeAttribute('hidden');
  1116. isCanvasHidden = false;
  1117. }
  1118. if (self.loadingIconDiv) {
  1119. div.removeChild(self.loadingIconDiv);
  1120. delete self.loadingIconDiv;
  1121. }
  1122. if (self.zoomLayer) {
  1123. // Zeroing the width and height causes Firefox to release graphics
  1124. // resources immediately, which can greatly reduce memory consumption.
  1125. var zoomLayerCanvas = self.zoomLayer.firstChild;
  1126. zoomLayerCanvas.width = 0;
  1127. zoomLayerCanvas.height = 0;
  1128. div.removeChild(self.zoomLayer);
  1129. self.zoomLayer = null;
  1130. }
  1131. self.error = error;
  1132. self.stats = pdfPage.stats;
  1133. if (self.onAfterDraw) {
  1134. self.onAfterDraw();
  1135. }
  1136. var event = document.createEvent('CustomEvent');
  1137. event.initCustomEvent('pagerendered', true, true, {
  1138. pageNumber: self.id,
  1139. cssTransform: false,
  1140. });
  1141. div.dispatchEvent(event);
  1142. if (!error) {
  1143. resolveRenderPromise(undefined);
  1144. } else {
  1145. rejectRenderPromise(error);
  1146. }
  1147. }
  1148. var renderContinueCallback = null;
  1149. if (this.renderingQueue) {
  1150. renderContinueCallback = function renderContinueCallback(cont) {
  1151. if (!self.renderingQueue.isHighestPriority(self)) {
  1152. self.renderingState = RenderingStates.PAUSED;
  1153. self.resume = function resumeCallback() {
  1154. self.renderingState = RenderingStates.RUNNING;
  1155. cont();
  1156. };
  1157. return;
  1158. }
  1159. if (isCanvasHidden) {
  1160. self.canvas.removeAttribute('hidden');
  1161. isCanvasHidden = false;
  1162. }
  1163. cont();
  1164. };
  1165. }
  1166. var transform = !outputScale.scaled ? null :
  1167. [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  1168. var renderContext = {
  1169. canvasContext: ctx,
  1170. transform: transform,
  1171. viewport: this.viewport,
  1172. // intent: 'default', // === 'display'
  1173. };
  1174. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  1175. renderTask.onContinue = renderContinueCallback;
  1176. this.renderTask.promise.then(
  1177. function pdfPageRenderCallback() {
  1178. pageViewDrawCallback(null);
  1179. if (textLayer) {
  1180. self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
  1181. function textContentResolved(textContent) {
  1182. textLayer.setTextContent(textContent);
  1183. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  1184. }
  1185. );
  1186. }
  1187. },
  1188. function pdfPageRenderError(error) {
  1189. pageViewDrawCallback(error);
  1190. }
  1191. );
  1192. if (this.annotationLayerFactory) {
  1193. if (!this.annotationLayer) {
  1194. this.annotationLayer = this.annotationLayerFactory.
  1195. createAnnotationLayerBuilder(div, this.pdfPage);
  1196. }
  1197. this.annotationLayer.render(this.viewport, 'display');
  1198. }
  1199. div.setAttribute('data-loaded', true);
  1200. if (self.onBeforeDraw) {
  1201. self.onBeforeDraw();
  1202. }
  1203. return promise;
  1204. },
  1205. beforePrint: function PDFPageView_beforePrint() {
  1206. var CustomStyle = PDFJS.CustomStyle;
  1207. var pdfPage = this.pdfPage;
  1208. var viewport = pdfPage.getViewport(1);
  1209. // Use the same hack we use for high dpi displays for printing to get
  1210. // better output until bug 811002 is fixed in FF.
  1211. var PRINT_OUTPUT_SCALE = 2;
  1212. var canvas = document.createElement('canvas');
  1213. // The logical size of the canvas.
  1214. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  1215. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  1216. // The rendered size of the canvas, relative to the size of canvasWrapper.
  1217. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  1218. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  1219. (1 / PRINT_OUTPUT_SCALE) + ')';
  1220. CustomStyle.setProp('transform' , canvas, cssScale);
  1221. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  1222. var printContainer = document.getElementById('printContainer');
  1223. var canvasWrapper = document.createElement('div');
  1224. canvasWrapper.appendChild(canvas);
  1225. printContainer.appendChild(canvasWrapper);
  1226. canvas.mozPrintCallback = function(obj) {
  1227. var ctx = obj.context;
  1228. ctx.save();
  1229. ctx.fillStyle = 'rgb(255, 255, 255)';
  1230. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1231. ctx.restore();
  1232. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1233. ctx._transformMatrix =
  1234. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  1235. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  1236. var renderContext = {
  1237. canvasContext: ctx,
  1238. viewport: viewport,
  1239. intent: 'print'
  1240. };
  1241. pdfPage.render(renderContext).promise.then(function() {
  1242. // Tell the printEngine that rendering this canvas/page has finished.
  1243. obj.done();
  1244. }, function(error) {
  1245. console.error(error);
  1246. // Tell the printEngine that rendering this canvas/page has failed.
  1247. // This will make the print proces stop.
  1248. if ('abort' in obj) {
  1249. obj.abort();
  1250. } else {
  1251. obj.done();
  1252. }
  1253. });
  1254. };
  1255. },
  1256. };
  1257. return PDFPageView;
  1258. })();
  1259. /**
  1260. * @typedef {Object} TextLayerBuilderOptions
  1261. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  1262. * @property {number} pageIndex - The page index.
  1263. * @property {PageViewport} viewport - The viewport of the text layer.
  1264. * @property {PDFFindController} findController
  1265. */
  1266. /**
  1267. * TextLayerBuilder provides text-selection functionality for the PDF.
  1268. * It does this by creating overlay divs over the PDF text. These divs
  1269. * contain text that matches the PDF text they are overlaying. This object
  1270. * also provides a way to highlight text that is being searched for.
  1271. * @class
  1272. */
  1273. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  1274. function TextLayerBuilder(options) {
  1275. this.textLayerDiv = options.textLayerDiv;
  1276. this.renderingDone = false;
  1277. this.divContentDone = false;
  1278. this.pageIdx = options.pageIndex;
  1279. this.pageNumber = this.pageIdx + 1;
  1280. this.matches = [];
  1281. this.viewport = options.viewport;
  1282. this.textDivs = [];
  1283. this.findController = options.findController || null;
  1284. this.textLayerRenderTask = null;
  1285. this._bindMouse();
  1286. }
  1287. TextLayerBuilder.prototype = {
  1288. _finishRendering: function TextLayerBuilder_finishRendering() {
  1289. this.renderingDone = true;
  1290. var endOfContent = document.createElement('div');
  1291. endOfContent.className = 'endOfContent';
  1292. this.textLayerDiv.appendChild(endOfContent);
  1293. var event = document.createEvent('CustomEvent');
  1294. event.initCustomEvent('textlayerrendered', true, true, {
  1295. pageNumber: this.pageNumber
  1296. });
  1297. this.textLayerDiv.dispatchEvent(event);
  1298. },
  1299. /**
  1300. * Renders the text layer.
  1301. * @param {number} timeout (optional) if specified, the rendering waits
  1302. * for specified amount of ms.
  1303. */
  1304. render: function TextLayerBuilder_render(timeout) {
  1305. if (!this.divContentDone || this.renderingDone) {
  1306. return;
  1307. }
  1308. if (this.textLayerRenderTask) {
  1309. this.textLayerRenderTask.cancel();
  1310. this.textLayerRenderTask = null;
  1311. }
  1312. this.textDivs = [];
  1313. var textLayerFrag = document.createDocumentFragment();
  1314. this.textLayerRenderTask = PDFJS.renderTextLayer({
  1315. textContent: this.textContent,
  1316. container: textLayerFrag,
  1317. viewport: this.viewport,
  1318. textDivs: this.textDivs,
  1319. timeout: timeout
  1320. });
  1321. this.textLayerRenderTask.promise.then(function () {
  1322. this.textLayerDiv.appendChild(textLayerFrag);
  1323. this._finishRendering();
  1324. this.updateMatches();
  1325. }.bind(this), function (reason) {
  1326. // canceled or failed to render text layer -- skipping errors
  1327. });
  1328. },
  1329. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  1330. if (this.textLayerRenderTask) {
  1331. this.textLayerRenderTask.cancel();
  1332. this.textLayerRenderTask = null;
  1333. }
  1334. this.textContent = textContent;
  1335. this.divContentDone = true;
  1336. },
  1337. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  1338. var i = 0;
  1339. var iIndex = 0;
  1340. var bidiTexts = this.textContent.items;
  1341. var end = bidiTexts.length - 1;
  1342. var queryLen = (this.findController === null ?
  1343. 0 : this.findController.state.query.length);
  1344. var ret = [];
  1345. for (var m = 0, len = matches.length; m < len; m++) {
  1346. // Calculate the start position.
  1347. var matchIdx = matches[m];
  1348. // Loop over the divIdxs.
  1349. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  1350. iIndex += bidiTexts[i].str.length;
  1351. i++;
  1352. }
  1353. if (i === bidiTexts.length) {
  1354. console.error('Could not find a matching mapping');
  1355. }
  1356. var match = {
  1357. begin: {
  1358. divIdx: i,
  1359. offset: matchIdx - iIndex
  1360. }
  1361. };
  1362. // Calculate the end position.
  1363. matchIdx += queryLen;
  1364. // Somewhat the same array as above, but use > instead of >= to get
  1365. // the end position right.
  1366. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  1367. iIndex += bidiTexts[i].str.length;
  1368. i++;
  1369. }
  1370. match.end = {
  1371. divIdx: i,
  1372. offset: matchIdx - iIndex
  1373. };
  1374. ret.push(match);
  1375. }
  1376. return ret;
  1377. },
  1378. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  1379. // Early exit if there is nothing to render.
  1380. if (matches.length === 0) {
  1381. return;
  1382. }
  1383. var bidiTexts = this.textContent.items;
  1384. var textDivs = this.textDivs;
  1385. var prevEnd = null;
  1386. var pageIdx = this.pageIdx;
  1387. var isSelectedPage = (this.findController === null ?
  1388. false : (pageIdx === this.findController.selected.pageIdx));
  1389. var selectedMatchIdx = (this.findController === null ?
  1390. -1 : this.findController.selected.matchIdx);
  1391. var highlightAll = (this.findController === null ?
  1392. false : this.findController.state.highlightAll);
  1393. var infinity = {
  1394. divIdx: -1,
  1395. offset: undefined
  1396. };
  1397. function beginText(begin, className) {
  1398. var divIdx = begin.divIdx;
  1399. textDivs[divIdx].textContent = '';
  1400. appendTextToDiv(divIdx, 0, begin.offset, className);
  1401. }
  1402. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  1403. var div = textDivs[divIdx];
  1404. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  1405. var node = document.createTextNode(content);
  1406. if (className) {
  1407. var span = document.createElement('span');
  1408. span.className = className;
  1409. span.appendChild(node);
  1410. div.appendChild(span);
  1411. return;
  1412. }
  1413. div.appendChild(node);
  1414. }
  1415. var i0 = selectedMatchIdx, i1 = i0 + 1;
  1416. if (highlightAll) {
  1417. i0 = 0;
  1418. i1 = matches.length;
  1419. } else if (!isSelectedPage) {
  1420. // Not highlighting all and this isn't the selected page, so do nothing.
  1421. return;
  1422. }
  1423. for (var i = i0; i < i1; i++) {
  1424. var match = matches[i];
  1425. var begin = match.begin;
  1426. var end = match.end;
  1427. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  1428. var highlightSuffix = (isSelected ? ' selected' : '');
  1429. if (this.findController) {
  1430. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  1431. begin.divIdx, end.divIdx);
  1432. }
  1433. // Match inside new div.
  1434. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  1435. // If there was a previous div, then add the text at the end.
  1436. if (prevEnd !== null) {
  1437. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1438. }
  1439. // Clear the divs and set the content until the starting point.
  1440. beginText(begin);
  1441. } else {
  1442. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  1443. }
  1444. if (begin.divIdx === end.divIdx) {
  1445. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  1446. 'highlight' + highlightSuffix);
  1447. } else {
  1448. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  1449. 'highlight begin' + highlightSuffix);
  1450. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  1451. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  1452. }
  1453. beginText(end, 'highlight end' + highlightSuffix);
  1454. }
  1455. prevEnd = end;
  1456. }
  1457. if (prevEnd) {
  1458. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1459. }
  1460. },
  1461. updateMatches: function TextLayerBuilder_updateMatches() {
  1462. // Only show matches when all rendering is done.
  1463. if (!this.renderingDone) {
  1464. return;
  1465. }
  1466. // Clear all matches.
  1467. var matches = this.matches;
  1468. var textDivs = this.textDivs;
  1469. var bidiTexts = this.textContent.items;
  1470. var clearedUntilDivIdx = -1;
  1471. // Clear all current matches.
  1472. for (var i = 0, len = matches.length; i < len; i++) {
  1473. var match = matches[i];
  1474. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  1475. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  1476. var div = textDivs[n];
  1477. div.textContent = bidiTexts[n].str;
  1478. div.className = '';
  1479. }
  1480. clearedUntilDivIdx = match.end.divIdx + 1;
  1481. }
  1482. if (this.findController === null || !this.findController.active) {
  1483. return;
  1484. }
  1485. // Convert the matches on the page controller into the match format
  1486. // used for the textLayer.
  1487. this.matches = this.convertMatches(this.findController === null ?
  1488. [] : (this.findController.pageMatches[this.pageIdx] || []));
  1489. this.renderMatches(this.matches);
  1490. },
  1491. /**
  1492. * Fixes text selection: adds additional div where mouse was clicked.
  1493. * This reduces flickering of the content if mouse slowly dragged down/up.
  1494. * @private
  1495. */
  1496. _bindMouse: function TextLayerBuilder_bindMouse() {
  1497. var div = this.textLayerDiv;
  1498. div.addEventListener('mousedown', function (e) {
  1499. var end = div.querySelector('.endOfContent');
  1500. if (!end) {
  1501. return;
  1502. }
  1503. // On non-Firefox browsers, the selection will feel better if the height
  1504. // of the endOfContent div will be adjusted to start at mouse click
  1505. // location -- this will avoid flickering when selections moves up.
  1506. // However it does not work when selection started on empty space.
  1507. var adjustTop = e.target !== div;
  1508. if (adjustTop) {
  1509. var divBounds = div.getBoundingClientRect();
  1510. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  1511. end.style.top = (r * 100).toFixed(2) + '%';
  1512. }
  1513. end.classList.add('active');
  1514. });
  1515. div.addEventListener('mouseup', function (e) {
  1516. var end = div.querySelector('.endOfContent');
  1517. if (!end) {
  1518. return;
  1519. }
  1520. end.style.top = '';
  1521. end.classList.remove('active');
  1522. });
  1523. },
  1524. };
  1525. return TextLayerBuilder;
  1526. })();
  1527. /**
  1528. * @constructor
  1529. * @implements IPDFTextLayerFactory
  1530. */
  1531. function DefaultTextLayerFactory() {}
  1532. DefaultTextLayerFactory.prototype = {
  1533. /**
  1534. * @param {HTMLDivElement} textLayerDiv
  1535. * @param {number} pageIndex
  1536. * @param {PageViewport} viewport
  1537. * @returns {TextLayerBuilder}
  1538. */
  1539. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  1540. return new TextLayerBuilder({
  1541. textLayerDiv: textLayerDiv,
  1542. pageIndex: pageIndex,
  1543. viewport: viewport
  1544. });
  1545. }
  1546. };
  1547. /**
  1548. * @typedef {Object} AnnotationLayerBuilderOptions
  1549. * @property {HTMLDivElement} pageDiv
  1550. * @property {PDFPage} pdfPage
  1551. * @property {IPDFLinkService} linkService
  1552. * @property {DownloadManager} downloadManager
  1553. */
  1554. /**
  1555. * @class
  1556. */
  1557. var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
  1558. /**
  1559. * @param {AnnotationLayerBuilderOptions} options
  1560. * @constructs AnnotationLayerBuilder
  1561. */
  1562. function AnnotationLayerBuilder(options) {
  1563. this.pageDiv = options.pageDiv;
  1564. this.pdfPage = options.pdfPage;
  1565. this.linkService = options.linkService;
  1566. this.downloadManager = options.downloadManager;
  1567. this.div = null;
  1568. }
  1569. AnnotationLayerBuilder.prototype =
  1570. /** @lends AnnotationLayerBuilder.prototype */ {
  1571. /**
  1572. * @param {PageViewport} viewport
  1573. * @param {string} intent (default value is 'display')
  1574. */
  1575. render: function AnnotationLayerBuilder_render(viewport, intent) {
  1576. var self = this;
  1577. var parameters = {
  1578. intent: (intent === undefined ? 'display' : intent),
  1579. };
  1580. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  1581. viewport = viewport.clone({ dontFlip: true });
  1582. parameters = {
  1583. viewport: viewport,
  1584. div: self.div,
  1585. annotations: annotations,
  1586. page: self.pdfPage,
  1587. linkService: self.linkService,
  1588. downloadManager: self.downloadManager
  1589. };
  1590. if (self.div) {
  1591. // If an annotationLayer already exists, refresh its children's
  1592. // transformation matrices.
  1593. PDFJS.AnnotationLayer.update(parameters);
  1594. } else {
  1595. // Create an annotation layer div and render the annotations
  1596. // if there is at least one annotation.
  1597. if (annotations.length === 0) {
  1598. return;
  1599. }
  1600. self.div = document.createElement('div');
  1601. self.div.className = 'annotationLayer';
  1602. self.pageDiv.appendChild(self.div);
  1603. parameters.div = self.div;
  1604. PDFJS.AnnotationLayer.render(parameters);
  1605. if (typeof mozL10n !== 'undefined') {
  1606. mozL10n.translate(self.div);
  1607. }
  1608. }
  1609. });
  1610. },
  1611. hide: function AnnotationLayerBuilder_hide() {
  1612. if (!this.div) {
  1613. return;
  1614. }
  1615. this.div.setAttribute('hidden', 'true');
  1616. }
  1617. };
  1618. return AnnotationLayerBuilder;
  1619. })();
  1620. /**
  1621. * @constructor
  1622. * @implements IPDFAnnotationLayerFactory
  1623. */
  1624. function DefaultAnnotationLayerFactory() {}
  1625. DefaultAnnotationLayerFactory.prototype = {
  1626. /**
  1627. * @param {HTMLDivElement} pageDiv
  1628. * @param {PDFPage} pdfPage
  1629. * @returns {AnnotationLayerBuilder}
  1630. */
  1631. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  1632. return new AnnotationLayerBuilder({
  1633. pageDiv: pageDiv,
  1634. pdfPage: pdfPage,
  1635. linkService: new SimpleLinkService(),
  1636. });
  1637. }
  1638. };
  1639. /**
  1640. * @typedef {Object} PDFViewerOptions
  1641. * @property {HTMLDivElement} container - The container for the viewer element.
  1642. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  1643. * @property {IPDFLinkService} linkService - The navigation/linking service.
  1644. * @property {DownloadManager} downloadManager - (optional) The download
  1645. * manager component.
  1646. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  1647. * queue object.
  1648. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  1649. * around the pages. The default is false.
  1650. */
  1651. /**
  1652. * Simple viewer control to display PDF content/pages.
  1653. * @class
  1654. * @implements {IRenderableView}
  1655. */
  1656. var PDFViewer = (function pdfViewer() {
  1657. function PDFPageViewBuffer(size) {
  1658. var data = [];
  1659. this.push = function cachePush(view) {
  1660. var i = data.indexOf(view);
  1661. if (i >= 0) {
  1662. data.splice(i, 1);
  1663. }
  1664. data.push(view);
  1665. if (data.length > size) {
  1666. data.shift().destroy();
  1667. }
  1668. };
  1669. this.resize = function (newSize) {
  1670. size = newSize;
  1671. while (data.length > size) {
  1672. data.shift().destroy();
  1673. }
  1674. };
  1675. }
  1676. function isSameScale(oldScale, newScale) {
  1677. if (newScale === oldScale) {
  1678. return true;
  1679. }
  1680. if (Math.abs(newScale - oldScale) < 1e-15) {
  1681. // Prevent unnecessary re-rendering of all pages when the scale
  1682. // changes only because of limited numerical precision.
  1683. return true;
  1684. }
  1685. return false;
  1686. }
  1687. /**
  1688. * @constructs PDFViewer
  1689. * @param {PDFViewerOptions} options
  1690. */
  1691. function PDFViewer(options) {
  1692. this.container = options.container;
  1693. this.viewer = options.viewer || options.container.firstElementChild;
  1694. this.linkService = options.linkService || new SimpleLinkService();
  1695. this.downloadManager = options.downloadManager || null;
  1696. this.removePageBorders = options.removePageBorders || false;
  1697. this.defaultRenderingQueue = !options.renderingQueue;
  1698. if (this.defaultRenderingQueue) {
  1699. // Custom rendering queue is not specified, using default one
  1700. this.renderingQueue = new PDFRenderingQueue();
  1701. this.renderingQueue.setViewer(this);
  1702. } else {
  1703. this.renderingQueue = options.renderingQueue;
  1704. }
  1705. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  1706. this.updateInProgress = false;
  1707. this.presentationModeState = PresentationModeState.UNKNOWN;
  1708. this._resetView();
  1709. if (this.removePageBorders) {
  1710. this.viewer.classList.add('removePageBorders');
  1711. }
  1712. }
  1713. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  1714. get pagesCount() {
  1715. return this._pages.length;
  1716. },
  1717. getPageView: function (index) {
  1718. return this._pages[index];
  1719. },
  1720. get currentPageNumber() {
  1721. return this._currentPageNumber;
  1722. },
  1723. set currentPageNumber(val) {
  1724. if (!this.pdfDocument) {
  1725. this._currentPageNumber = val;
  1726. return;
  1727. }
  1728. var event = document.createEvent('UIEvents');
  1729. event.initUIEvent('pagechange', true, true, window, 0);
  1730. event.updateInProgress = this.updateInProgress;
  1731. if (!(0 < val && val <= this.pagesCount)) {
  1732. event.pageNumber = this._currentPageNumber;
  1733. event.previousPageNumber = val;
  1734. this.container.dispatchEvent(event);
  1735. return;
  1736. }
  1737. event.previousPageNumber = this._currentPageNumber;
  1738. this._currentPageNumber = val;
  1739. event.pageNumber = val;
  1740. this.container.dispatchEvent(event);
  1741. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  1742. if (this.updateInProgress) {
  1743. return;
  1744. }
  1745. this.scrollPageIntoView(val);
  1746. },
  1747. /**
  1748. * @returns {number}
  1749. */
  1750. get currentScale() {
  1751. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  1752. DEFAULT_SCALE;
  1753. },
  1754. /**
  1755. * @param {number} val - Scale of the pages in percents.
  1756. */
  1757. set currentScale(val) {
  1758. if (isNaN(val)) {
  1759. throw new Error('Invalid numeric scale');
  1760. }
  1761. if (!this.pdfDocument) {
  1762. this._currentScale = val;
  1763. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  1764. return;
  1765. }
  1766. this._setScale(val, false);
  1767. },
  1768. /**
  1769. * @returns {string}
  1770. */
  1771. get currentScaleValue() {
  1772. return this._currentScaleValue;
  1773. },
  1774. /**
  1775. * @param val - The scale of the pages (in percent or predefined value).
  1776. */
  1777. set currentScaleValue(val) {
  1778. if (!this.pdfDocument) {
  1779. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  1780. this._currentScaleValue = val;
  1781. return;
  1782. }
  1783. this._setScale(val, false);
  1784. },
  1785. /**
  1786. * @returns {number}
  1787. */
  1788. get pagesRotation() {
  1789. return this._pagesRotation;
  1790. },
  1791. /**
  1792. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  1793. */
  1794. set pagesRotation(rotation) {
  1795. this._pagesRotation = rotation;
  1796. for (var i = 0, l = this._pages.length; i < l; i++) {
  1797. var pageView = this._pages[i];
  1798. pageView.update(pageView.scale, rotation);
  1799. }
  1800. this._setScale(this._currentScaleValue, true);
  1801. if (this.defaultRenderingQueue) {
  1802. this.update();
  1803. }
  1804. },
  1805. /**
  1806. * @param pdfDocument {PDFDocument}
  1807. */
  1808. setDocument: function (pdfDocument) {
  1809. if (this.pdfDocument) {
  1810. this._resetView();
  1811. }
  1812. this.pdfDocument = pdfDocument;
  1813. if (!pdfDocument) {
  1814. return;
  1815. }
  1816. var pagesCount = pdfDocument.numPages;
  1817. var self = this;
  1818. var resolvePagesPromise;
  1819. var pagesPromise = new Promise(function (resolve) {
  1820. resolvePagesPromise = resolve;
  1821. });
  1822. this.pagesPromise = pagesPromise;
  1823. pagesPromise.then(function () {
  1824. var event = document.createEvent('CustomEvent');
  1825. event.initCustomEvent('pagesloaded', true, true, {
  1826. pagesCount: pagesCount
  1827. });
  1828. self.container.dispatchEvent(event);
  1829. });
  1830. var isOnePageRenderedResolved = false;
  1831. var resolveOnePageRendered = null;
  1832. var onePageRendered = new Promise(function (resolve) {
  1833. resolveOnePageRendered = resolve;
  1834. });
  1835. this.onePageRendered = onePageRendered;
  1836. var bindOnAfterAndBeforeDraw = function (pageView) {
  1837. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  1838. // Add the page to the buffer at the start of drawing. That way it can
  1839. // be evicted from the buffer and destroyed even if we pause its
  1840. // rendering.
  1841. self._buffer.push(this);
  1842. };
  1843. // when page is painted, using the image as thumbnail base
  1844. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  1845. if (!isOnePageRenderedResolved) {
  1846. isOnePageRenderedResolved = true;
  1847. resolveOnePageRendered();
  1848. }
  1849. };
  1850. };
  1851. var firstPagePromise = pdfDocument.getPage(1);
  1852. this.firstPagePromise = firstPagePromise;
  1853. // Fetch a single page so we can get a viewport that will be the default
  1854. // viewport for all pages
  1855. return firstPagePromise.then(function(pdfPage) {
  1856. var scale = this.currentScale;
  1857. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  1858. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1859. var textLayerFactory = null;
  1860. if (!PDFJS.disableTextLayer) {
  1861. textLayerFactory = this;
  1862. }
  1863. var pageView = new PDFPageView({
  1864. container: this.viewer,
  1865. id: pageNum,
  1866. scale: scale,
  1867. defaultViewport: viewport.clone(),
  1868. renderingQueue: this.renderingQueue,
  1869. textLayerFactory: textLayerFactory,
  1870. annotationLayerFactory: this
  1871. });
  1872. bindOnAfterAndBeforeDraw(pageView);
  1873. this._pages.push(pageView);
  1874. }
  1875. var linkService = this.linkService;
  1876. // Fetch all the pages since the viewport is needed before printing
  1877. // starts to create the correct size canvas. Wait until one page is
  1878. // rendered so we don't tie up too many resources early on.
  1879. onePageRendered.then(function () {
  1880. if (!PDFJS.disableAutoFetch) {
  1881. var getPagesLeft = pagesCount;
  1882. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1883. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  1884. var pageView = self._pages[pageNum - 1];
  1885. if (!pageView.pdfPage) {
  1886. pageView.setPdfPage(pdfPage);
  1887. }
  1888. linkService.cachePageRef(pageNum, pdfPage.ref);
  1889. getPagesLeft--;
  1890. if (!getPagesLeft) {
  1891. resolvePagesPromise();
  1892. }
  1893. }.bind(null, pageNum));
  1894. }
  1895. } else {
  1896. // XXX: Printing is semi-broken with auto fetch disabled.
  1897. resolvePagesPromise();
  1898. }
  1899. });
  1900. var event = document.createEvent('CustomEvent');
  1901. event.initCustomEvent('pagesinit', true, true, null);
  1902. self.container.dispatchEvent(event);
  1903. if (this.defaultRenderingQueue) {
  1904. this.update();
  1905. }
  1906. if (this.findController) {
  1907. this.findController.resolveFirstPage();
  1908. }
  1909. }.bind(this));
  1910. },
  1911. _resetView: function () {
  1912. this._pages = [];
  1913. this._currentPageNumber = 1;
  1914. this._currentScale = UNKNOWN_SCALE;
  1915. this._currentScaleValue = null;
  1916. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  1917. this._location = null;
  1918. this._pagesRotation = 0;
  1919. this._pagesRequests = [];
  1920. var container = this.viewer;
  1921. while (container.hasChildNodes()) {
  1922. container.removeChild(container.lastChild);
  1923. }
  1924. },
  1925. _scrollUpdate: function PDFViewer_scrollUpdate() {
  1926. if (this.pagesCount === 0) {
  1927. return;
  1928. }
  1929. this.update();
  1930. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  1931. this._pages[i].updatePosition();
  1932. }
  1933. },
  1934. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  1935. newScale, newValue, preset) {
  1936. var event = document.createEvent('UIEvents');
  1937. event.initUIEvent('scalechange', true, true, window, 0);
  1938. event.scale = newScale;
  1939. if (preset) {
  1940. event.presetValue = newValue;
  1941. }
  1942. this.container.dispatchEvent(event);
  1943. },
  1944. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  1945. newScale, newValue, noScroll, preset) {
  1946. this._currentScaleValue = newValue;
  1947. if (isSameScale(this._currentScale, newScale)) {
  1948. if (preset) {
  1949. this._setScaleDispatchEvent(newScale, newValue, true);
  1950. }
  1951. return;
  1952. }
  1953. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  1954. this._pages[i].update(newScale);
  1955. }
  1956. this._currentScale = newScale;
  1957. if (!noScroll) {
  1958. var page = this._currentPageNumber, dest;
  1959. if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
  1960. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  1961. page = this._location.pageNumber;
  1962. dest = [null, { name: 'XYZ' }, this._location.left,
  1963. this._location.top, null];
  1964. }
  1965. this.scrollPageIntoView(page, dest);
  1966. }
  1967. this._setScaleDispatchEvent(newScale, newValue, preset);
  1968. if (this.defaultRenderingQueue) {
  1969. this.update();
  1970. }
  1971. },
  1972. _setScale: function pdfViewer_setScale(value, noScroll) {
  1973. var scale = parseFloat(value);
  1974. if (scale > 0) {
  1975. this._setScaleUpdatePages(scale, value, noScroll, false);
  1976. } else {
  1977. var currentPage = this._pages[this._currentPageNumber - 1];
  1978. if (!currentPage) {
  1979. return;
  1980. }
  1981. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  1982. 0 : SCROLLBAR_PADDING;
  1983. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  1984. 0 : VERTICAL_PADDING;
  1985. var pageWidthScale = (this.container.clientWidth - hPadding) /
  1986. currentPage.width * currentPage.scale;
  1987. var pageHeightScale = (this.container.clientHeight - vPadding) /
  1988. currentPage.height * currentPage.scale;
  1989. switch (value) {
  1990. case 'page-actual':
  1991. scale = 1;
  1992. break;
  1993. case 'page-width':
  1994. scale = pageWidthScale;
  1995. break;
  1996. case 'page-height':
  1997. scale = pageHeightScale;
  1998. break;
  1999. case 'page-fit':
  2000. scale = Math.min(pageWidthScale, pageHeightScale);
  2001. break;
  2002. case 'auto':
  2003. var isLandscape = (currentPage.width > currentPage.height);
  2004. // For pages in landscape mode, fit the page height to the viewer
  2005. // *unless* the page would thus become too wide to fit horizontally.
  2006. var horizontalScale = isLandscape ?
  2007. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  2008. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  2009. break;
  2010. default:
  2011. console.error('pdfViewSetScale: \'' + value +
  2012. '\' is an unknown zoom value.');
  2013. return;
  2014. }
  2015. this._setScaleUpdatePages(scale, value, noScroll, true);
  2016. }
  2017. },
  2018. /**
  2019. * Scrolls page into view.
  2020. * @param {number} pageNumber
  2021. * @param {Array} dest - (optional) original PDF destination array:
  2022. * <page-ref> </XYZ|FitXXX> <args..>
  2023. */
  2024. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  2025. dest) {
  2026. if (!this.pdfDocument) {
  2027. return;
  2028. }
  2029. var pageView = this._pages[pageNumber - 1];
  2030. if (this.isInPresentationMode) {
  2031. if (this._currentPageNumber !== pageView.id) {
  2032. // Avoid breaking getVisiblePages in presentation mode.
  2033. this.currentPageNumber = pageView.id;
  2034. return;
  2035. }
  2036. dest = null;
  2037. // Fixes the case when PDF has different page sizes.
  2038. this._setScale(this._currentScaleValue, true);
  2039. }
  2040. if (!dest) {
  2041. scrollIntoView(pageView.div);
  2042. return;
  2043. }
  2044. var x = 0, y = 0;
  2045. var width = 0, height = 0, widthScale, heightScale;
  2046. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  2047. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  2048. pageView.scale / CSS_UNITS;
  2049. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  2050. pageView.scale / CSS_UNITS;
  2051. var scale = 0;
  2052. switch (dest[1].name) {
  2053. case 'XYZ':
  2054. x = dest[2];
  2055. y = dest[3];
  2056. scale = dest[4];
  2057. // If x and/or y coordinates are not supplied, default to
  2058. // _top_ left of the page (not the obvious bottom left,
  2059. // since aligning the bottom of the intended page with the
  2060. // top of the window is rarely helpful).
  2061. x = x !== null ? x : 0;
  2062. y = y !== null ? y : pageHeight;
  2063. break;
  2064. case 'Fit':
  2065. case 'FitB':
  2066. scale = 'page-fit';
  2067. break;
  2068. case 'FitH':
  2069. case 'FitBH':
  2070. y = dest[2];
  2071. scale = 'page-width';
  2072. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  2073. // parameter should maintain the position relative to the new page.
  2074. if (y === null && this._location) {
  2075. x = this._location.left;
  2076. y = this._location.top;
  2077. }
  2078. break;
  2079. case 'FitV':
  2080. case 'FitBV':
  2081. x = dest[2];
  2082. width = pageWidth;
  2083. height = pageHeight;
  2084. scale = 'page-height';
  2085. break;
  2086. case 'FitR':
  2087. x = dest[2];
  2088. y = dest[3];
  2089. width = dest[4] - x;
  2090. height = dest[5] - y;
  2091. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  2092. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  2093. widthScale = (this.container.clientWidth - hPadding) /
  2094. width / CSS_UNITS;
  2095. heightScale = (this.container.clientHeight - vPadding) /
  2096. height / CSS_UNITS;
  2097. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  2098. break;
  2099. default:
  2100. return;
  2101. }
  2102. if (scale && scale !== this._currentScale) {
  2103. this.currentScaleValue = scale;
  2104. } else if (this._currentScale === UNKNOWN_SCALE) {
  2105. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  2106. }
  2107. if (scale === 'page-fit' && !dest[4]) {
  2108. scrollIntoView(pageView.div);
  2109. return;
  2110. }
  2111. var boundingRect = [
  2112. pageView.viewport.convertToViewportPoint(x, y),
  2113. pageView.viewport.convertToViewportPoint(x + width, y + height)
  2114. ];
  2115. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  2116. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  2117. scrollIntoView(pageView.div, { left: left, top: top });
  2118. },
  2119. _updateLocation: function (firstPage) {
  2120. var currentScale = this._currentScale;
  2121. var currentScaleValue = this._currentScaleValue;
  2122. var normalizedScaleValue =
  2123. parseFloat(currentScaleValue) === currentScale ?
  2124. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  2125. var pageNumber = firstPage.id;
  2126. var pdfOpenParams = '#page=' + pageNumber;
  2127. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  2128. var currentPageView = this._pages[pageNumber - 1];
  2129. var container = this.container;
  2130. var topLeft = currentPageView.getPagePoint(
  2131. (container.scrollLeft - firstPage.x),
  2132. (container.scrollTop - firstPage.y));
  2133. var intLeft = Math.round(topLeft[0]);
  2134. var intTop = Math.round(topLeft[1]);
  2135. pdfOpenParams += ',' + intLeft + ',' + intTop;
  2136. this._location = {
  2137. pageNumber: pageNumber,
  2138. scale: normalizedScaleValue,
  2139. top: intTop,
  2140. left: intLeft,
  2141. pdfOpenParams: pdfOpenParams
  2142. };
  2143. },
  2144. update: function PDFViewer_update() {
  2145. var visible = this._getVisiblePages();
  2146. var visiblePages = visible.views;
  2147. if (visiblePages.length === 0) {
  2148. return;
  2149. }
  2150. this.updateInProgress = true;
  2151. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  2152. 2 * visiblePages.length + 1);
  2153. this._buffer.resize(suggestedCacheSize);
  2154. this.renderingQueue.renderHighestPriority(visible);
  2155. var currentId = this._currentPageNumber;
  2156. var firstPage = visible.first;
  2157. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  2158. i < ii; ++i) {
  2159. var page = visiblePages[i];
  2160. if (page.percent < 100) {
  2161. break;
  2162. }
  2163. if (page.id === currentId) {
  2164. stillFullyVisible = true;
  2165. break;
  2166. }
  2167. }
  2168. if (!stillFullyVisible) {
  2169. currentId = visiblePages[0].id;
  2170. }
  2171. if (!this.isInPresentationMode) {
  2172. this.currentPageNumber = currentId;
  2173. }
  2174. this._updateLocation(firstPage);
  2175. this.updateInProgress = false;
  2176. var event = document.createEvent('UIEvents');
  2177. event.initUIEvent('updateviewarea', true, true, window, 0);
  2178. event.location = this._location;
  2179. this.container.dispatchEvent(event);
  2180. },
  2181. containsElement: function (element) {
  2182. return this.container.contains(element);
  2183. },
  2184. focus: function () {
  2185. this.container.focus();
  2186. },
  2187. get isInPresentationMode() {
  2188. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  2189. },
  2190. get isChangingPresentationMode() {
  2191. return this.presentationModeState === PresentationModeState.CHANGING;
  2192. },
  2193. get isHorizontalScrollbarEnabled() {
  2194. return (this.isInPresentationMode ?
  2195. false : (this.container.scrollWidth > this.container.clientWidth));
  2196. },
  2197. _getVisiblePages: function () {
  2198. if (!this.isInPresentationMode) {
  2199. return getVisibleElements(this.container, this._pages, true);
  2200. } else {
  2201. // The algorithm in getVisibleElements doesn't work in all browsers and
  2202. // configurations when presentation mode is active.
  2203. var visible = [];
  2204. var currentPage = this._pages[this._currentPageNumber - 1];
  2205. visible.push({ id: currentPage.id, view: currentPage });
  2206. return { first: currentPage, last: currentPage, views: visible };
  2207. }
  2208. },
  2209. cleanup: function () {
  2210. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2211. if (this._pages[i] &&
  2212. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  2213. this._pages[i].reset();
  2214. }
  2215. }
  2216. },
  2217. /**
  2218. * @param {PDFPageView} pageView
  2219. * @returns {PDFPage}
  2220. * @private
  2221. */
  2222. _ensurePdfPageLoaded: function (pageView) {
  2223. if (pageView.pdfPage) {
  2224. return Promise.resolve(pageView.pdfPage);
  2225. }
  2226. var pageNumber = pageView.id;
  2227. if (this._pagesRequests[pageNumber]) {
  2228. return this._pagesRequests[pageNumber];
  2229. }
  2230. var promise = this.pdfDocument.getPage(pageNumber).then(
  2231. function (pdfPage) {
  2232. pageView.setPdfPage(pdfPage);
  2233. this._pagesRequests[pageNumber] = null;
  2234. return pdfPage;
  2235. }.bind(this));
  2236. this._pagesRequests[pageNumber] = promise;
  2237. return promise;
  2238. },
  2239. forceRendering: function (currentlyVisiblePages) {
  2240. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  2241. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  2242. this._pages,
  2243. this.scroll.down);
  2244. if (pageView) {
  2245. this._ensurePdfPageLoaded(pageView).then(function () {
  2246. this.renderingQueue.renderView(pageView);
  2247. }.bind(this));
  2248. return true;
  2249. }
  2250. return false;
  2251. },
  2252. getPageTextContent: function (pageIndex) {
  2253. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  2254. return page.getTextContent({ normalizeWhitespace: true });
  2255. });
  2256. },
  2257. /**
  2258. * @param {HTMLDivElement} textLayerDiv
  2259. * @param {number} pageIndex
  2260. * @param {PageViewport} viewport
  2261. * @returns {TextLayerBuilder}
  2262. */
  2263. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2264. return new TextLayerBuilder({
  2265. textLayerDiv: textLayerDiv,
  2266. pageIndex: pageIndex,
  2267. viewport: viewport,
  2268. findController: this.isInPresentationMode ? null : this.findController
  2269. });
  2270. },
  2271. /**
  2272. * @param {HTMLDivElement} pageDiv
  2273. * @param {PDFPage} pdfPage
  2274. * @returns {AnnotationLayerBuilder}
  2275. */
  2276. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  2277. return new AnnotationLayerBuilder({
  2278. pageDiv: pageDiv,
  2279. pdfPage: pdfPage,
  2280. linkService: this.linkService,
  2281. downloadManager: this.downloadManager
  2282. });
  2283. },
  2284. setFindController: function (findController) {
  2285. this.findController = findController;
  2286. },
  2287. };
  2288. return PDFViewer;
  2289. })();
  2290. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  2291. function SimpleLinkService() {}
  2292. SimpleLinkService.prototype = {
  2293. /**
  2294. * @returns {number}
  2295. */
  2296. get page() {
  2297. return 0;
  2298. },
  2299. /**
  2300. * @param {number} value
  2301. */
  2302. set page(value) {},
  2303. /**
  2304. * @param dest - The PDF destination object.
  2305. */
  2306. navigateTo: function (dest) {},
  2307. /**
  2308. * @param dest - The PDF destination object.
  2309. * @returns {string} The hyperlink to the PDF object.
  2310. */
  2311. getDestinationHash: function (dest) {
  2312. return '#';
  2313. },
  2314. /**
  2315. * @param hash - The PDF parameters/hash.
  2316. * @returns {string} The hyperlink to the PDF object.
  2317. */
  2318. getAnchorUrl: function (hash) {
  2319. return '#';
  2320. },
  2321. /**
  2322. * @param {string} hash
  2323. */
  2324. setHash: function (hash) {},
  2325. /**
  2326. * @param {string} action
  2327. */
  2328. executeNamedAction: function (action) {},
  2329. /**
  2330. * @param {number} pageNum - page number.
  2331. * @param {Object} pageRef - reference to the page.
  2332. */
  2333. cachePageRef: function (pageNum, pageRef) {}
  2334. };
  2335. return SimpleLinkService;
  2336. })();
  2337. var PDFHistory = (function () {
  2338. function PDFHistory(options) {
  2339. this.linkService = options.linkService;
  2340. this.initialized = false;
  2341. this.initialDestination = null;
  2342. this.initialBookmark = null;
  2343. }
  2344. PDFHistory.prototype = {
  2345. /**
  2346. * @param {string} fingerprint
  2347. * @param {IPDFLinkService} linkService
  2348. */
  2349. initialize: function pdfHistoryInitialize(fingerprint) {
  2350. this.initialized = true;
  2351. this.reInitialized = false;
  2352. this.allowHashChange = true;
  2353. this.historyUnlocked = true;
  2354. this.isViewerInPresentationMode = false;
  2355. this.previousHash = window.location.hash.substring(1);
  2356. this.currentBookmark = '';
  2357. this.currentPage = 0;
  2358. this.updatePreviousBookmark = false;
  2359. this.previousBookmark = '';
  2360. this.previousPage = 0;
  2361. this.nextHashParam = '';
  2362. this.fingerprint = fingerprint;
  2363. this.currentUid = this.uid = 0;
  2364. this.current = {};
  2365. var state = window.history.state;
  2366. if (this._isStateObjectDefined(state)) {
  2367. // This corresponds to navigating back to the document
  2368. // from another page in the browser history.
  2369. if (state.target.dest) {
  2370. this.initialDestination = state.target.dest;
  2371. } else {
  2372. this.initialBookmark = state.target.hash;
  2373. }
  2374. this.currentUid = state.uid;
  2375. this.uid = state.uid + 1;
  2376. this.current = state.target;
  2377. } else {
  2378. // This corresponds to the loading of a new document.
  2379. if (state && state.fingerprint &&
  2380. this.fingerprint !== state.fingerprint) {
  2381. // Reinitialize the browsing history when a new document
  2382. // is opened in the web viewer.
  2383. this.reInitialized = true;
  2384. }
  2385. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  2386. }
  2387. var self = this;
  2388. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  2389. if (!self.historyUnlocked) {
  2390. return;
  2391. }
  2392. if (evt.state) {
  2393. // Move back/forward in the history.
  2394. self._goTo(evt.state);
  2395. return;
  2396. }
  2397. // If the state is not set, then the user tried to navigate to a
  2398. // different hash by manually editing the URL and pressing Enter, or by
  2399. // clicking on an in-page link (e.g. the "current view" link).
  2400. // Save the current view state to the browser history.
  2401. // Note: In Firefox, history.null could also be null after an in-page
  2402. // navigation to the same URL, and without dispatching the popstate
  2403. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  2404. if (self.uid === 0) {
  2405. // Replace the previous state if it was not explicitly set.
  2406. var previousParams = (self.previousHash && self.currentBookmark &&
  2407. self.previousHash !== self.currentBookmark) ?
  2408. {hash: self.currentBookmark, page: self.currentPage} :
  2409. {page: 1};
  2410. replacePreviousHistoryState(previousParams, function() {
  2411. updateHistoryWithCurrentHash();
  2412. });
  2413. } else {
  2414. updateHistoryWithCurrentHash();
  2415. }
  2416. }, false);
  2417. function updateHistoryWithCurrentHash() {
  2418. self.previousHash = window.location.hash.slice(1);
  2419. self._pushToHistory({hash: self.previousHash}, false, true);
  2420. self._updatePreviousBookmark();
  2421. }
  2422. function replacePreviousHistoryState(params, callback) {
  2423. // To modify the previous history entry, the following happens:
  2424. // 1. history.back()
  2425. // 2. _pushToHistory, which calls history.replaceState( ... )
  2426. // 3. history.forward()
  2427. // Because a navigation via the history API does not immediately update
  2428. // the history state, the popstate event is used for synchronization.
  2429. self.historyUnlocked = false;
  2430. // Suppress the hashchange event to avoid side effects caused by
  2431. // navigating back and forward.
  2432. self.allowHashChange = false;
  2433. window.addEventListener('popstate', rewriteHistoryAfterBack);
  2434. history.back();
  2435. function rewriteHistoryAfterBack() {
  2436. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  2437. window.addEventListener('popstate', rewriteHistoryAfterForward);
  2438. self._pushToHistory(params, false, true);
  2439. history.forward();
  2440. }
  2441. function rewriteHistoryAfterForward() {
  2442. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  2443. self.allowHashChange = true;
  2444. self.historyUnlocked = true;
  2445. callback();
  2446. }
  2447. }
  2448. function pdfHistoryBeforeUnload() {
  2449. var previousParams = self._getPreviousParams(null, true);
  2450. if (previousParams) {
  2451. var replacePrevious = (!self.current.dest &&
  2452. self.current.hash !== self.previousHash);
  2453. self._pushToHistory(previousParams, false, replacePrevious);
  2454. self._updatePreviousBookmark();
  2455. }
  2456. // Remove the event listener when navigating away from the document,
  2457. // since 'beforeunload' prevents Firefox from caching the document.
  2458. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  2459. false);
  2460. }
  2461. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2462. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  2463. // If the entire viewer (including the PDF file) is cached in
  2464. // the browser, we need to reattach the 'beforeunload' event listener
  2465. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  2466. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2467. }, false);
  2468. window.addEventListener('presentationmodechanged', function(e) {
  2469. self.isViewerInPresentationMode = !!e.detail.active;
  2470. });
  2471. },
  2472. clearHistoryState: function pdfHistory_clearHistoryState() {
  2473. this._pushOrReplaceState(null, true);
  2474. },
  2475. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  2476. return (state && state.uid >= 0 &&
  2477. state.fingerprint && this.fingerprint === state.fingerprint &&
  2478. state.target && state.target.hash) ? true : false;
  2479. },
  2480. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  2481. replace) {
  2482. if (replace) {
  2483. window.history.replaceState(stateObj, '');
  2484. } else {
  2485. window.history.pushState(stateObj, '');
  2486. }
  2487. },
  2488. get isHashChangeUnlocked() {
  2489. if (!this.initialized) {
  2490. return true;
  2491. }
  2492. return this.allowHashChange;
  2493. },
  2494. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  2495. if (this.updatePreviousBookmark &&
  2496. this.currentBookmark && this.currentPage) {
  2497. this.previousBookmark = this.currentBookmark;
  2498. this.previousPage = this.currentPage;
  2499. this.updatePreviousBookmark = false;
  2500. }
  2501. },
  2502. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  2503. pageNum) {
  2504. if (this.initialized) {
  2505. this.currentBookmark = bookmark.substring(1);
  2506. this.currentPage = pageNum | 0;
  2507. this._updatePreviousBookmark();
  2508. }
  2509. },
  2510. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  2511. if (this.initialized) {
  2512. this.nextHashParam = param;
  2513. }
  2514. },
  2515. push: function pdfHistoryPush(params, isInitialBookmark) {
  2516. if (!(this.initialized && this.historyUnlocked)) {
  2517. return;
  2518. }
  2519. if (params.dest && !params.hash) {
  2520. params.hash = (this.current.hash && this.current.dest &&
  2521. this.current.dest === params.dest) ?
  2522. this.current.hash :
  2523. this.linkService.getDestinationHash(params.dest).split('#')[1];
  2524. }
  2525. if (params.page) {
  2526. params.page |= 0;
  2527. }
  2528. if (isInitialBookmark) {
  2529. var target = window.history.state.target;
  2530. if (!target) {
  2531. // Invoked when the user specifies an initial bookmark,
  2532. // thus setting initialBookmark, when the document is loaded.
  2533. this._pushToHistory(params, false);
  2534. this.previousHash = window.location.hash.substring(1);
  2535. }
  2536. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  2537. if (target) {
  2538. // If the current document is reloaded,
  2539. // avoid creating duplicate entries in the history.
  2540. this._updatePreviousBookmark();
  2541. }
  2542. return;
  2543. }
  2544. if (this.nextHashParam) {
  2545. if (this.nextHashParam === params.hash) {
  2546. this.nextHashParam = null;
  2547. this.updatePreviousBookmark = true;
  2548. return;
  2549. } else {
  2550. this.nextHashParam = null;
  2551. }
  2552. }
  2553. if (params.hash) {
  2554. if (this.current.hash) {
  2555. if (this.current.hash !== params.hash) {
  2556. this._pushToHistory(params, true);
  2557. } else {
  2558. if (!this.current.page && params.page) {
  2559. this._pushToHistory(params, false, true);
  2560. }
  2561. this.updatePreviousBookmark = true;
  2562. }
  2563. } else {
  2564. this._pushToHistory(params, true);
  2565. }
  2566. } else if (this.current.page && params.page &&
  2567. this.current.page !== params.page) {
  2568. this._pushToHistory(params, true);
  2569. }
  2570. },
  2571. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  2572. beforeUnload) {
  2573. if (!(this.currentBookmark && this.currentPage)) {
  2574. return null;
  2575. } else if (this.updatePreviousBookmark) {
  2576. this.updatePreviousBookmark = false;
  2577. }
  2578. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  2579. // Prevent the history from getting stuck in the current state,
  2580. // effectively preventing the user from going back/forward in
  2581. // the history.
  2582. //
  2583. // This happens if the current position in the document didn't change
  2584. // when the history was previously updated. The reasons for this are
  2585. // either:
  2586. // 1. The current zoom value is such that the document does not need to,
  2587. // or cannot, be scrolled to display the destination.
  2588. // 2. The previous destination is broken, and doesn't actally point to a
  2589. // position within the document.
  2590. // (This is either due to a bad PDF generator, or the user making a
  2591. // mistake when entering a destination in the hash parameters.)
  2592. return null;
  2593. }
  2594. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  2595. if (this.previousBookmark === this.currentBookmark) {
  2596. return null;
  2597. }
  2598. } else if (this.current.page || onlyCheckPage) {
  2599. if (this.previousPage === this.currentPage) {
  2600. return null;
  2601. }
  2602. } else {
  2603. return null;
  2604. }
  2605. var params = {hash: this.currentBookmark, page: this.currentPage};
  2606. if (this.isViewerInPresentationMode) {
  2607. params.hash = null;
  2608. }
  2609. return params;
  2610. },
  2611. _stateObj: function pdfHistory_stateObj(params) {
  2612. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  2613. },
  2614. _pushToHistory: function pdfHistory_pushToHistory(params,
  2615. addPrevious, overwrite) {
  2616. if (!this.initialized) {
  2617. return;
  2618. }
  2619. if (!params.hash && params.page) {
  2620. params.hash = ('page=' + params.page);
  2621. }
  2622. if (addPrevious && !overwrite) {
  2623. var previousParams = this._getPreviousParams();
  2624. if (previousParams) {
  2625. var replacePrevious = (!this.current.dest &&
  2626. this.current.hash !== this.previousHash);
  2627. this._pushToHistory(previousParams, false, replacePrevious);
  2628. }
  2629. }
  2630. this._pushOrReplaceState(this._stateObj(params),
  2631. (overwrite || this.uid === 0));
  2632. this.currentUid = this.uid++;
  2633. this.current = params;
  2634. this.updatePreviousBookmark = true;
  2635. },
  2636. _goTo: function pdfHistory_goTo(state) {
  2637. if (!(this.initialized && this.historyUnlocked &&
  2638. this._isStateObjectDefined(state))) {
  2639. return;
  2640. }
  2641. if (!this.reInitialized && state.uid < this.currentUid) {
  2642. var previousParams = this._getPreviousParams(true);
  2643. if (previousParams) {
  2644. this._pushToHistory(this.current, false);
  2645. this._pushToHistory(previousParams, false);
  2646. this.currentUid = state.uid;
  2647. window.history.back();
  2648. return;
  2649. }
  2650. }
  2651. this.historyUnlocked = false;
  2652. if (state.target.dest) {
  2653. this.linkService.navigateTo(state.target.dest);
  2654. } else {
  2655. this.linkService.setHash(state.target.hash);
  2656. }
  2657. this.currentUid = state.uid;
  2658. if (state.uid > this.uid) {
  2659. this.uid = state.uid;
  2660. }
  2661. this.current = state.target;
  2662. this.updatePreviousBookmark = true;
  2663. var currentHash = window.location.hash.substring(1);
  2664. if (this.previousHash !== currentHash) {
  2665. this.allowHashChange = false;
  2666. }
  2667. this.previousHash = currentHash;
  2668. this.historyUnlocked = true;
  2669. },
  2670. back: function pdfHistoryBack() {
  2671. this.go(-1);
  2672. },
  2673. forward: function pdfHistoryForward() {
  2674. this.go(1);
  2675. },
  2676. go: function pdfHistoryGo(direction) {
  2677. if (this.initialized && this.historyUnlocked) {
  2678. var state = window.history.state;
  2679. if (direction === -1 && state && state.uid > 0) {
  2680. window.history.back();
  2681. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  2682. window.history.forward();
  2683. }
  2684. }
  2685. }
  2686. };
  2687. return PDFHistory;
  2688. })();
  2689. var DownloadManager = (function DownloadManagerClosure() {
  2690. function download(blobUrl, filename) {
  2691. var a = document.createElement('a');
  2692. if (a.click) {
  2693. // Use a.click() if available. Otherwise, Chrome might show
  2694. // "Unsafe JavaScript attempt to initiate a navigation change
  2695. // for frame with URL" and not open the PDF at all.
  2696. // Supported by (not mentioned = untested):
  2697. // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
  2698. // - Chrome 19 - 26 (18- does not support a.click)
  2699. // - Opera 9 - 12.15
  2700. // - Internet Explorer 6 - 10
  2701. // - Safari 6 (5.1- does not support a.click)
  2702. a.href = blobUrl;
  2703. a.target = '_parent';
  2704. // Use a.download if available. This increases the likelihood that
  2705. // the file is downloaded instead of opened by another PDF plugin.
  2706. if ('download' in a) {
  2707. a.download = filename;
  2708. }
  2709. // <a> must be in the document for IE and recent Firefox versions.
  2710. // (otherwise .click() is ignored)
  2711. (document.body || document.documentElement).appendChild(a);
  2712. a.click();
  2713. a.parentNode.removeChild(a);
  2714. } else {
  2715. if (window.top === window &&
  2716. blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  2717. // If _parent == self, then opening an identical URL with different
  2718. // location hash will only cause a navigation, not a download.
  2719. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  2720. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  2721. }
  2722. window.open(blobUrl, '_parent');
  2723. }
  2724. }
  2725. function DownloadManager() {}
  2726. DownloadManager.prototype = {
  2727. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  2728. if (!PDFJS.isValidUrl(url, true)) {
  2729. return; // restricted/invalid URL
  2730. }
  2731. download(url + '#pdfjs.action=download', filename);
  2732. },
  2733. downloadData: function DownloadManager_downloadData(data, filename,
  2734. contentType) {
  2735. if (navigator.msSaveBlob) { // IE10 and above
  2736. return navigator.msSaveBlob(new Blob([data], { type: contentType }),
  2737. filename);
  2738. }
  2739. var blobUrl = PDFJS.createObjectURL(data, contentType);
  2740. download(blobUrl, filename);
  2741. },
  2742. download: function DownloadManager_download(blob, url, filename) {
  2743. if (!URL) {
  2744. // URL.createObjectURL is not supported
  2745. this.downloadUrl(url, filename);
  2746. return;
  2747. }
  2748. if (navigator.msSaveBlob) {
  2749. // IE10 / IE11
  2750. if (!navigator.msSaveBlob(blob, filename)) {
  2751. this.downloadUrl(url, filename);
  2752. }
  2753. return;
  2754. }
  2755. var blobUrl = URL.createObjectURL(blob);
  2756. download(blobUrl, filename);
  2757. }
  2758. };
  2759. return DownloadManager;
  2760. })();
  2761. PDFJS.PDFViewer = PDFViewer;
  2762. PDFJS.PDFPageView = PDFPageView;
  2763. PDFJS.PDFLinkService = PDFLinkService;
  2764. PDFJS.TextLayerBuilder = TextLayerBuilder;
  2765. PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2766. PDFJS.AnnotationLayerBuilder = AnnotationLayerBuilder;
  2767. PDFJS.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  2768. PDFJS.PDFHistory = PDFHistory;
  2769. PDFJS.DownloadManager = DownloadManager;
  2770. PDFJS.ProgressBar = ProgressBar;
  2771. }).call((typeof window === 'undefined') ? this : window);