pdf_viewer.js 103 KB

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