pdf_viewer.js 100 KB

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