pdf_viewer.js 99 KB

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