2
0

pdf_viewer.js 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274
  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 outputScale = this.outputScale;
  955. var pixelsInViewport = this.viewport.width * this.viewport.height;
  956. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  957. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  958. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  959. PDFJS.maxCanvasPixels) {
  960. isScalingRestricted = true;
  961. }
  962. }
  963. if (this.canvas) {
  964. if (PDFJS.useOnlyCssZoom ||
  965. (this.hasRestrictedScaling && isScalingRestricted)) {
  966. this.cssTransform(this.canvas, true);
  967. var event = document.createEvent('CustomEvent');
  968. event.initCustomEvent('pagerendered', true, true, {
  969. pageNumber: this.id,
  970. cssTransform: true,
  971. });
  972. this.div.dispatchEvent(event);
  973. return;
  974. }
  975. if (!this.zoomLayer) {
  976. this.zoomLayer = this.canvas.parentNode;
  977. this.zoomLayer.style.position = 'absolute';
  978. }
  979. }
  980. if (this.zoomLayer) {
  981. this.cssTransform(this.zoomLayer.firstChild);
  982. }
  983. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
  984. },
  985. /**
  986. * Called when moved in the parent's container.
  987. */
  988. updatePosition: function PDFPageView_updatePosition() {
  989. if (this.textLayer) {
  990. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  991. }
  992. },
  993. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  994. // Scale canvas, canvas wrapper, and page container.
  995. var width = this.viewport.width;
  996. var height = this.viewport.height;
  997. var div = this.div;
  998. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  999. Math.floor(width) + 'px';
  1000. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  1001. Math.floor(height) + 'px';
  1002. // The canvas may have been originally rotated, rotate relative to that.
  1003. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  1004. var absRotation = Math.abs(relativeRotation);
  1005. var scaleX = 1, scaleY = 1;
  1006. if (absRotation === 90 || absRotation === 270) {
  1007. // Scale x and y because of the rotation.
  1008. scaleX = height / width;
  1009. scaleY = width / height;
  1010. }
  1011. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  1012. 'scale(' + scaleX + ',' + scaleY + ')';
  1013. CustomStyle.setProp('transform', canvas, cssTransform);
  1014. if (this.textLayer) {
  1015. // Rotating the text layer is more complicated since the divs inside the
  1016. // the text layer are rotated.
  1017. // TODO: This could probably be simplified by drawing the text layer in
  1018. // one orientation then rotating overall.
  1019. var textLayerViewport = this.textLayer.viewport;
  1020. var textRelativeRotation = this.viewport.rotation -
  1021. textLayerViewport.rotation;
  1022. var textAbsRotation = Math.abs(textRelativeRotation);
  1023. var scale = width / textLayerViewport.width;
  1024. if (textAbsRotation === 90 || textAbsRotation === 270) {
  1025. scale = width / textLayerViewport.height;
  1026. }
  1027. var textLayerDiv = this.textLayer.textLayerDiv;
  1028. var transX, transY;
  1029. switch (textAbsRotation) {
  1030. case 0:
  1031. transX = transY = 0;
  1032. break;
  1033. case 90:
  1034. transX = 0;
  1035. transY = '-' + textLayerDiv.style.height;
  1036. break;
  1037. case 180:
  1038. transX = '-' + textLayerDiv.style.width;
  1039. transY = '-' + textLayerDiv.style.height;
  1040. break;
  1041. case 270:
  1042. transX = '-' + textLayerDiv.style.width;
  1043. transY = 0;
  1044. break;
  1045. default:
  1046. console.error('Bad rotation value.');
  1047. break;
  1048. }
  1049. CustomStyle.setProp('transform', textLayerDiv,
  1050. 'rotate(' + textAbsRotation + 'deg) ' +
  1051. 'scale(' + scale + ', ' + scale + ') ' +
  1052. 'translate(' + transX + ', ' + transY + ')');
  1053. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  1054. }
  1055. if (redrawAnnotations && this.annotationLayer) {
  1056. this.annotationLayer.setupAnnotations(this.viewport);
  1057. }
  1058. },
  1059. get width() {
  1060. return this.viewport.width;
  1061. },
  1062. get height() {
  1063. return this.viewport.height;
  1064. },
  1065. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  1066. return this.viewport.convertToPdfPoint(x, y);
  1067. },
  1068. draw: function PDFPageView_draw() {
  1069. if (this.renderingState !== RenderingStates.INITIAL) {
  1070. console.error('Must be in new state before drawing');
  1071. }
  1072. this.renderingState = RenderingStates.RUNNING;
  1073. var pdfPage = this.pdfPage;
  1074. var viewport = this.viewport;
  1075. var div = this.div;
  1076. // Wrap the canvas so if it has a css transform for highdpi the overflow
  1077. // will be hidden in FF.
  1078. var canvasWrapper = document.createElement('div');
  1079. canvasWrapper.style.width = div.style.width;
  1080. canvasWrapper.style.height = div.style.height;
  1081. canvasWrapper.classList.add('canvasWrapper');
  1082. var canvas = document.createElement('canvas');
  1083. canvas.id = 'page' + this.id;
  1084. canvas.setAttribute('hidden', 'hidden');
  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. var isCanvasHidden = true;
  1093. this.canvas = canvas;
  1094. var ctx = canvas.getContext('2d', {alpha: false});
  1095. var outputScale = getOutputScale(ctx);
  1096. this.outputScale = outputScale;
  1097. if (PDFJS.useOnlyCssZoom) {
  1098. var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
  1099. // Use a scale that will make the canvas be the original intended size
  1100. // of the page.
  1101. outputScale.sx *= actualSizeViewport.width / viewport.width;
  1102. outputScale.sy *= actualSizeViewport.height / viewport.height;
  1103. outputScale.scaled = true;
  1104. }
  1105. if (PDFJS.maxCanvasPixels > 0) {
  1106. var pixelsInViewport = viewport.width * viewport.height;
  1107. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  1108. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  1109. outputScale.sx = maxScale;
  1110. outputScale.sy = maxScale;
  1111. outputScale.scaled = true;
  1112. this.hasRestrictedScaling = true;
  1113. } else {
  1114. this.hasRestrictedScaling = false;
  1115. }
  1116. }
  1117. var sfx = approximateFraction(outputScale.sx);
  1118. var sfy = approximateFraction(outputScale.sy);
  1119. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  1120. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  1121. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  1122. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  1123. // Add the viewport so it's known what it was originally drawn with.
  1124. canvas._viewport = viewport;
  1125. var textLayerDiv = null;
  1126. var textLayer = null;
  1127. if (this.textLayerFactory) {
  1128. textLayerDiv = document.createElement('div');
  1129. textLayerDiv.className = 'textLayer';
  1130. textLayerDiv.style.width = canvasWrapper.style.width;
  1131. textLayerDiv.style.height = canvasWrapper.style.height;
  1132. if (this.annotationLayer && this.annotationLayer.div) {
  1133. // annotationLayer needs to stay on top
  1134. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  1135. } else {
  1136. div.appendChild(textLayerDiv);
  1137. }
  1138. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  1139. this.id - 1,
  1140. this.viewport);
  1141. }
  1142. this.textLayer = textLayer;
  1143. var resolveRenderPromise, rejectRenderPromise;
  1144. var promise = new Promise(function (resolve, reject) {
  1145. resolveRenderPromise = resolve;
  1146. rejectRenderPromise = reject;
  1147. });
  1148. // Rendering area
  1149. var self = this;
  1150. function pageViewDrawCallback(error) {
  1151. // The renderTask may have been replaced by a new one, so only remove
  1152. // the reference to the renderTask if it matches the one that is
  1153. // triggering this callback.
  1154. if (renderTask === self.renderTask) {
  1155. self.renderTask = null;
  1156. }
  1157. if (error === 'cancelled') {
  1158. rejectRenderPromise(error);
  1159. return;
  1160. }
  1161. self.renderingState = RenderingStates.FINISHED;
  1162. if (self.loadingIconDiv) {
  1163. div.removeChild(self.loadingIconDiv);
  1164. delete self.loadingIconDiv;
  1165. }
  1166. if (self.zoomLayer) {
  1167. // Zeroing the width and height causes Firefox to release graphics
  1168. // resources immediately, which can greatly reduce memory consumption.
  1169. var zoomLayerCanvas = self.zoomLayer.firstChild;
  1170. zoomLayerCanvas.width = 0;
  1171. zoomLayerCanvas.height = 0;
  1172. div.removeChild(self.zoomLayer);
  1173. self.zoomLayer = null;
  1174. }
  1175. self.error = error;
  1176. self.stats = pdfPage.stats;
  1177. if (self.onAfterDraw) {
  1178. self.onAfterDraw();
  1179. }
  1180. var event = document.createEvent('CustomEvent');
  1181. event.initCustomEvent('pagerendered', true, true, {
  1182. pageNumber: self.id,
  1183. cssTransform: false,
  1184. });
  1185. div.dispatchEvent(event);
  1186. if (!error) {
  1187. resolveRenderPromise(undefined);
  1188. } else {
  1189. rejectRenderPromise(error);
  1190. }
  1191. }
  1192. var renderContinueCallback = null;
  1193. if (this.renderingQueue) {
  1194. renderContinueCallback = function renderContinueCallback(cont) {
  1195. if (!self.renderingQueue.isHighestPriority(self)) {
  1196. self.renderingState = RenderingStates.PAUSED;
  1197. self.resume = function resumeCallback() {
  1198. self.renderingState = RenderingStates.RUNNING;
  1199. cont();
  1200. };
  1201. return;
  1202. }
  1203. if (isCanvasHidden) {
  1204. self.canvas.removeAttribute('hidden');
  1205. isCanvasHidden = false;
  1206. }
  1207. cont();
  1208. };
  1209. }
  1210. var transform = !outputScale.scaled ? null :
  1211. [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  1212. var renderContext = {
  1213. canvasContext: ctx,
  1214. transform: transform,
  1215. viewport: this.viewport,
  1216. // intent: 'default', // === 'display'
  1217. };
  1218. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  1219. renderTask.onContinue = renderContinueCallback;
  1220. this.renderTask.promise.then(
  1221. function pdfPageRenderCallback() {
  1222. pageViewDrawCallback(null);
  1223. if (textLayer) {
  1224. self.pdfPage.getTextContent().then(
  1225. function textContentResolved(textContent) {
  1226. textLayer.setTextContent(textContent);
  1227. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  1228. }
  1229. );
  1230. }
  1231. },
  1232. function pdfPageRenderError(error) {
  1233. pageViewDrawCallback(error);
  1234. }
  1235. );
  1236. if (this.annotationsLayerFactory) {
  1237. if (!this.annotationLayer) {
  1238. this.annotationLayer = this.annotationsLayerFactory.
  1239. createAnnotationsLayerBuilder(div, this.pdfPage);
  1240. }
  1241. this.annotationLayer.setupAnnotations(this.viewport);
  1242. }
  1243. div.setAttribute('data-loaded', true);
  1244. if (self.onBeforeDraw) {
  1245. self.onBeforeDraw();
  1246. }
  1247. return promise;
  1248. },
  1249. beforePrint: function PDFPageView_beforePrint() {
  1250. var pdfPage = this.pdfPage;
  1251. var viewport = pdfPage.getViewport(1);
  1252. // Use the same hack we use for high dpi displays for printing to get
  1253. // better output until bug 811002 is fixed in FF.
  1254. var PRINT_OUTPUT_SCALE = 2;
  1255. var canvas = document.createElement('canvas');
  1256. // The logical size of the canvas.
  1257. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  1258. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  1259. // The rendered size of the canvas, relative to the size of canvasWrapper.
  1260. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  1261. canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
  1262. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  1263. (1 / PRINT_OUTPUT_SCALE) + ')';
  1264. CustomStyle.setProp('transform' , canvas, cssScale);
  1265. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  1266. var printContainer = document.getElementById('printContainer');
  1267. var canvasWrapper = document.createElement('div');
  1268. canvasWrapper.style.width = viewport.width + 'pt';
  1269. canvasWrapper.style.height = viewport.height + 'pt';
  1270. canvasWrapper.appendChild(canvas);
  1271. printContainer.appendChild(canvasWrapper);
  1272. canvas.mozPrintCallback = function(obj) {
  1273. var ctx = obj.context;
  1274. ctx.save();
  1275. ctx.fillStyle = 'rgb(255, 255, 255)';
  1276. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1277. ctx.restore();
  1278. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1279. ctx._transformMatrix =
  1280. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  1281. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  1282. var renderContext = {
  1283. canvasContext: ctx,
  1284. viewport: viewport,
  1285. intent: 'print'
  1286. };
  1287. pdfPage.render(renderContext).promise.then(function() {
  1288. // Tell the printEngine that rendering this canvas/page has finished.
  1289. obj.done();
  1290. }, function(error) {
  1291. console.error(error);
  1292. // Tell the printEngine that rendering this canvas/page has failed.
  1293. // This will make the print proces stop.
  1294. if ('abort' in obj) {
  1295. obj.abort();
  1296. } else {
  1297. obj.done();
  1298. }
  1299. });
  1300. };
  1301. },
  1302. };
  1303. return PDFPageView;
  1304. })();
  1305. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  1306. var NonWhitespaceRegexp = /\S/;
  1307. function isAllWhitespace(str) {
  1308. return !NonWhitespaceRegexp.test(str);
  1309. }
  1310. /**
  1311. * @typedef {Object} TextLayerBuilderOptions
  1312. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  1313. * @property {number} pageIndex - The page index.
  1314. * @property {PageViewport} viewport - The viewport of the text layer.
  1315. * @property {PDFFindController} findController
  1316. */
  1317. /**
  1318. * TextLayerBuilder provides text-selection functionality for the PDF.
  1319. * It does this by creating overlay divs over the PDF text. These divs
  1320. * contain text that matches the PDF text they are overlaying. This object
  1321. * also provides a way to highlight text that is being searched for.
  1322. * @class
  1323. */
  1324. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  1325. function TextLayerBuilder(options) {
  1326. this.textLayerDiv = options.textLayerDiv;
  1327. this.renderingDone = false;
  1328. this.divContentDone = false;
  1329. this.pageIdx = options.pageIndex;
  1330. this.pageNumber = this.pageIdx + 1;
  1331. this.matches = [];
  1332. this.viewport = options.viewport;
  1333. this.textDivs = [];
  1334. this.findController = options.findController || null;
  1335. this._bindMouse();
  1336. }
  1337. TextLayerBuilder.prototype = {
  1338. _finishRendering: function TextLayerBuilder_finishRendering() {
  1339. this.renderingDone = true;
  1340. var endOfContent = document.createElement('div');
  1341. endOfContent.className = 'endOfContent';
  1342. this.textLayerDiv.appendChild(endOfContent);
  1343. var event = document.createEvent('CustomEvent');
  1344. event.initCustomEvent('textlayerrendered', true, true, {
  1345. pageNumber: this.pageNumber
  1346. });
  1347. this.textLayerDiv.dispatchEvent(event);
  1348. },
  1349. renderLayer: function TextLayerBuilder_renderLayer() {
  1350. var textLayerFrag = document.createDocumentFragment();
  1351. var textDivs = this.textDivs;
  1352. var textDivsLength = textDivs.length;
  1353. var canvas = document.createElement('canvas');
  1354. var ctx = canvas.getContext('2d', {alpha: false});
  1355. // No point in rendering many divs as it would make the browser
  1356. // unusable even after the divs are rendered.
  1357. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  1358. this._finishRendering();
  1359. return;
  1360. }
  1361. var lastFontSize;
  1362. var lastFontFamily;
  1363. for (var i = 0; i < textDivsLength; i++) {
  1364. var textDiv = textDivs[i];
  1365. if (textDiv.dataset.isWhitespace !== undefined) {
  1366. continue;
  1367. }
  1368. var fontSize = textDiv.style.fontSize;
  1369. var fontFamily = textDiv.style.fontFamily;
  1370. // Only build font string and set to context if different from last.
  1371. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  1372. ctx.font = fontSize + ' ' + fontFamily;
  1373. lastFontSize = fontSize;
  1374. lastFontFamily = fontFamily;
  1375. }
  1376. var width = ctx.measureText(textDiv.textContent).width;
  1377. if (width > 0) {
  1378. textLayerFrag.appendChild(textDiv);
  1379. var transform;
  1380. if (textDiv.dataset.canvasWidth !== undefined) {
  1381. // Dataset values come of type string.
  1382. var textScale = textDiv.dataset.canvasWidth / width;
  1383. transform = 'scaleX(' + textScale + ')';
  1384. } else {
  1385. transform = '';
  1386. }
  1387. var rotation = textDiv.dataset.angle;
  1388. if (rotation) {
  1389. transform = 'rotate(' + rotation + 'deg) ' + transform;
  1390. }
  1391. if (transform) {
  1392. CustomStyle.setProp('transform' , textDiv, transform);
  1393. }
  1394. }
  1395. }
  1396. this.textLayerDiv.appendChild(textLayerFrag);
  1397. this._finishRendering();
  1398. this.updateMatches();
  1399. },
  1400. /**
  1401. * Renders the text layer.
  1402. * @param {number} timeout (optional) if specified, the rendering waits
  1403. * for specified amount of ms.
  1404. */
  1405. render: function TextLayerBuilder_render(timeout) {
  1406. if (!this.divContentDone || this.renderingDone) {
  1407. return;
  1408. }
  1409. if (this.renderTimer) {
  1410. clearTimeout(this.renderTimer);
  1411. this.renderTimer = null;
  1412. }
  1413. if (!timeout) { // Render right away
  1414. this.renderLayer();
  1415. } else { // Schedule
  1416. var self = this;
  1417. this.renderTimer = setTimeout(function() {
  1418. self.renderLayer();
  1419. self.renderTimer = null;
  1420. }, timeout);
  1421. }
  1422. },
  1423. appendText: function TextLayerBuilder_appendText(geom, styles) {
  1424. var style = styles[geom.fontName];
  1425. var textDiv = document.createElement('div');
  1426. this.textDivs.push(textDiv);
  1427. if (isAllWhitespace(geom.str)) {
  1428. textDiv.dataset.isWhitespace = true;
  1429. return;
  1430. }
  1431. var tx = PDFJS.Util.transform(this.viewport.transform, geom.transform);
  1432. var angle = Math.atan2(tx[1], tx[0]);
  1433. if (style.vertical) {
  1434. angle += Math.PI / 2;
  1435. }
  1436. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  1437. var fontAscent = fontHeight;
  1438. if (style.ascent) {
  1439. fontAscent = style.ascent * fontAscent;
  1440. } else if (style.descent) {
  1441. fontAscent = (1 + style.descent) * fontAscent;
  1442. }
  1443. var left;
  1444. var top;
  1445. if (angle === 0) {
  1446. left = tx[4];
  1447. top = tx[5] - fontAscent;
  1448. } else {
  1449. left = tx[4] + (fontAscent * Math.sin(angle));
  1450. top = tx[5] - (fontAscent * Math.cos(angle));
  1451. }
  1452. textDiv.style.left = left + 'px';
  1453. textDiv.style.top = top + 'px';
  1454. textDiv.style.fontSize = fontHeight + 'px';
  1455. textDiv.style.fontFamily = style.fontFamily;
  1456. textDiv.textContent = geom.str;
  1457. // |fontName| is only used by the Font Inspector. This test will succeed
  1458. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  1459. // not worth the effort to do a more accurate test.
  1460. if (PDFJS.pdfBug) {
  1461. textDiv.dataset.fontName = geom.fontName;
  1462. }
  1463. // Storing into dataset will convert number into string.
  1464. if (angle !== 0) {
  1465. textDiv.dataset.angle = angle * (180 / Math.PI);
  1466. }
  1467. // We don't bother scaling single-char text divs, because it has very
  1468. // little effect on text highlighting. This makes scrolling on docs with
  1469. // lots of such divs a lot faster.
  1470. if (geom.str.length > 1) {
  1471. if (style.vertical) {
  1472. textDiv.dataset.canvasWidth = geom.height * this.viewport.scale;
  1473. } else {
  1474. textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
  1475. }
  1476. }
  1477. },
  1478. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  1479. this.textContent = textContent;
  1480. var textItems = textContent.items;
  1481. for (var i = 0, len = textItems.length; i < len; i++) {
  1482. this.appendText(textItems[i], textContent.styles);
  1483. }
  1484. this.divContentDone = true;
  1485. },
  1486. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  1487. var i = 0;
  1488. var iIndex = 0;
  1489. var bidiTexts = this.textContent.items;
  1490. var end = bidiTexts.length - 1;
  1491. var queryLen = (this.findController === null ?
  1492. 0 : this.findController.state.query.length);
  1493. var ret = [];
  1494. for (var m = 0, len = matches.length; m < len; m++) {
  1495. // Calculate the start position.
  1496. var matchIdx = matches[m];
  1497. // Loop over the divIdxs.
  1498. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  1499. iIndex += bidiTexts[i].str.length;
  1500. i++;
  1501. }
  1502. if (i === bidiTexts.length) {
  1503. console.error('Could not find a matching mapping');
  1504. }
  1505. var match = {
  1506. begin: {
  1507. divIdx: i,
  1508. offset: matchIdx - iIndex
  1509. }
  1510. };
  1511. // Calculate the end position.
  1512. matchIdx += queryLen;
  1513. // Somewhat the same array as above, but use > instead of >= to get
  1514. // the end position right.
  1515. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  1516. iIndex += bidiTexts[i].str.length;
  1517. i++;
  1518. }
  1519. match.end = {
  1520. divIdx: i,
  1521. offset: matchIdx - iIndex
  1522. };
  1523. ret.push(match);
  1524. }
  1525. return ret;
  1526. },
  1527. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  1528. // Early exit if there is nothing to render.
  1529. if (matches.length === 0) {
  1530. return;
  1531. }
  1532. var bidiTexts = this.textContent.items;
  1533. var textDivs = this.textDivs;
  1534. var prevEnd = null;
  1535. var pageIdx = this.pageIdx;
  1536. var isSelectedPage = (this.findController === null ?
  1537. false : (pageIdx === this.findController.selected.pageIdx));
  1538. var selectedMatchIdx = (this.findController === null ?
  1539. -1 : this.findController.selected.matchIdx);
  1540. var highlightAll = (this.findController === null ?
  1541. false : this.findController.state.highlightAll);
  1542. var infinity = {
  1543. divIdx: -1,
  1544. offset: undefined
  1545. };
  1546. function beginText(begin, className) {
  1547. var divIdx = begin.divIdx;
  1548. textDivs[divIdx].textContent = '';
  1549. appendTextToDiv(divIdx, 0, begin.offset, className);
  1550. }
  1551. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  1552. var div = textDivs[divIdx];
  1553. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  1554. var node = document.createTextNode(content);
  1555. if (className) {
  1556. var span = document.createElement('span');
  1557. span.className = className;
  1558. span.appendChild(node);
  1559. div.appendChild(span);
  1560. return;
  1561. }
  1562. div.appendChild(node);
  1563. }
  1564. var i0 = selectedMatchIdx, i1 = i0 + 1;
  1565. if (highlightAll) {
  1566. i0 = 0;
  1567. i1 = matches.length;
  1568. } else if (!isSelectedPage) {
  1569. // Not highlighting all and this isn't the selected page, so do nothing.
  1570. return;
  1571. }
  1572. for (var i = i0; i < i1; i++) {
  1573. var match = matches[i];
  1574. var begin = match.begin;
  1575. var end = match.end;
  1576. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  1577. var highlightSuffix = (isSelected ? ' selected' : '');
  1578. if (this.findController) {
  1579. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  1580. begin.divIdx, end.divIdx);
  1581. }
  1582. // Match inside new div.
  1583. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  1584. // If there was a previous div, then add the text at the end.
  1585. if (prevEnd !== null) {
  1586. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1587. }
  1588. // Clear the divs and set the content until the starting point.
  1589. beginText(begin);
  1590. } else {
  1591. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  1592. }
  1593. if (begin.divIdx === end.divIdx) {
  1594. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  1595. 'highlight' + highlightSuffix);
  1596. } else {
  1597. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  1598. 'highlight begin' + highlightSuffix);
  1599. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  1600. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  1601. }
  1602. beginText(end, 'highlight end' + highlightSuffix);
  1603. }
  1604. prevEnd = end;
  1605. }
  1606. if (prevEnd) {
  1607. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1608. }
  1609. },
  1610. updateMatches: function TextLayerBuilder_updateMatches() {
  1611. // Only show matches when all rendering is done.
  1612. if (!this.renderingDone) {
  1613. return;
  1614. }
  1615. // Clear all matches.
  1616. var matches = this.matches;
  1617. var textDivs = this.textDivs;
  1618. var bidiTexts = this.textContent.items;
  1619. var clearedUntilDivIdx = -1;
  1620. // Clear all current matches.
  1621. for (var i = 0, len = matches.length; i < len; i++) {
  1622. var match = matches[i];
  1623. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  1624. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  1625. var div = textDivs[n];
  1626. div.textContent = bidiTexts[n].str;
  1627. div.className = '';
  1628. }
  1629. clearedUntilDivIdx = match.end.divIdx + 1;
  1630. }
  1631. if (this.findController === null || !this.findController.active) {
  1632. return;
  1633. }
  1634. // Convert the matches on the page controller into the match format
  1635. // used for the textLayer.
  1636. this.matches = this.convertMatches(this.findController === null ?
  1637. [] : (this.findController.pageMatches[this.pageIdx] || []));
  1638. this.renderMatches(this.matches);
  1639. },
  1640. /**
  1641. * Fixes text selection: adds additional div where mouse was clicked.
  1642. * This reduces flickering of the content if mouse slowly dragged down/up.
  1643. * @private
  1644. */
  1645. _bindMouse: function TextLayerBuilder_bindMouse() {
  1646. var div = this.textLayerDiv;
  1647. div.addEventListener('mousedown', function (e) {
  1648. var end = div.querySelector('.endOfContent');
  1649. if (!end) {
  1650. return;
  1651. }
  1652. // On non-Firefox browsers, the selection will feel better if the height
  1653. // of the endOfContent div will be adjusted to start at mouse click
  1654. // location -- this will avoid flickering when selections moves up.
  1655. // However it does not work when selection started on empty space.
  1656. var adjustTop = e.target !== div;
  1657. if (adjustTop) {
  1658. var divBounds = div.getBoundingClientRect();
  1659. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  1660. end.style.top = (r * 100).toFixed(2) + '%';
  1661. }
  1662. end.classList.add('active');
  1663. });
  1664. div.addEventListener('mouseup', function (e) {
  1665. var end = div.querySelector('.endOfContent');
  1666. if (!end) {
  1667. return;
  1668. }
  1669. end.style.top = '';
  1670. end.classList.remove('active');
  1671. });
  1672. },
  1673. };
  1674. return TextLayerBuilder;
  1675. })();
  1676. /**
  1677. * @constructor
  1678. * @implements IPDFTextLayerFactory
  1679. */
  1680. function DefaultTextLayerFactory() {}
  1681. DefaultTextLayerFactory.prototype = {
  1682. /**
  1683. * @param {HTMLDivElement} textLayerDiv
  1684. * @param {number} pageIndex
  1685. * @param {PageViewport} viewport
  1686. * @returns {TextLayerBuilder}
  1687. */
  1688. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  1689. return new TextLayerBuilder({
  1690. textLayerDiv: textLayerDiv,
  1691. pageIndex: pageIndex,
  1692. viewport: viewport
  1693. });
  1694. }
  1695. };
  1696. /**
  1697. * @typedef {Object} AnnotationsLayerBuilderOptions
  1698. * @property {HTMLDivElement} pageDiv
  1699. * @property {PDFPage} pdfPage
  1700. * @property {IPDFLinkService} linkService
  1701. */
  1702. /**
  1703. * @class
  1704. */
  1705. var AnnotationsLayerBuilder = (function AnnotationsLayerBuilderClosure() {
  1706. /**
  1707. * @param {AnnotationsLayerBuilderOptions} options
  1708. * @constructs AnnotationsLayerBuilder
  1709. */
  1710. function AnnotationsLayerBuilder(options) {
  1711. this.pageDiv = options.pageDiv;
  1712. this.pdfPage = options.pdfPage;
  1713. this.linkService = options.linkService;
  1714. this.div = null;
  1715. }
  1716. AnnotationsLayerBuilder.prototype =
  1717. /** @lends AnnotationsLayerBuilder.prototype */ {
  1718. /**
  1719. * @param {PageViewport} viewport
  1720. */
  1721. setupAnnotations:
  1722. function AnnotationsLayerBuilder_setupAnnotations(viewport) {
  1723. function bindLink(link, dest) {
  1724. link.href = linkService.getDestinationHash(dest);
  1725. link.onclick = function annotationsLayerBuilderLinksOnclick() {
  1726. if (dest) {
  1727. linkService.navigateTo(dest);
  1728. }
  1729. return false;
  1730. };
  1731. if (dest) {
  1732. link.className = 'internalLink';
  1733. }
  1734. }
  1735. function bindNamedAction(link, action) {
  1736. link.href = linkService.getAnchorUrl('');
  1737. link.onclick = function annotationsLayerBuilderNamedActionOnClick() {
  1738. linkService.executeNamedAction(action);
  1739. return false;
  1740. };
  1741. link.className = 'internalLink';
  1742. }
  1743. var linkService = this.linkService;
  1744. var pdfPage = this.pdfPage;
  1745. var self = this;
  1746. pdfPage.getAnnotations().then(function (annotationsData) {
  1747. viewport = viewport.clone({ dontFlip: true });
  1748. var transform = viewport.transform;
  1749. var transformStr = 'matrix(' + transform.join(',') + ')';
  1750. var data, element, i, ii;
  1751. if (self.div) {
  1752. // If an annotationLayer already exists, refresh its children's
  1753. // transformation matrices
  1754. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1755. data = annotationsData[i];
  1756. element = self.div.querySelector(
  1757. '[data-annotation-id="' + data.id + '"]');
  1758. if (element) {
  1759. CustomStyle.setProp('transform', element, transformStr);
  1760. }
  1761. }
  1762. // See PDFPageView.reset()
  1763. self.div.removeAttribute('hidden');
  1764. } else {
  1765. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1766. data = annotationsData[i];
  1767. if (!data || !data.hasHtml) {
  1768. continue;
  1769. }
  1770. element = PDFJS.AnnotationUtils.getHtmlElement(data,
  1771. pdfPage.commonObjs);
  1772. element.setAttribute('data-annotation-id', data.id);
  1773. if (typeof mozL10n !== 'undefined') {
  1774. mozL10n.translate(element);
  1775. }
  1776. var rect = data.rect;
  1777. var view = pdfPage.view;
  1778. rect = PDFJS.Util.normalizeRect([
  1779. rect[0],
  1780. view[3] - rect[1] + view[1],
  1781. rect[2],
  1782. view[3] - rect[3] + view[1]
  1783. ]);
  1784. element.style.left = rect[0] + 'px';
  1785. element.style.top = rect[1] + 'px';
  1786. element.style.position = 'absolute';
  1787. CustomStyle.setProp('transform', element, transformStr);
  1788. var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
  1789. CustomStyle.setProp('transformOrigin', element, transformOriginStr);
  1790. if (data.subtype === 'Link' && !data.url) {
  1791. var link = element.getElementsByTagName('a')[0];
  1792. if (link) {
  1793. if (data.action) {
  1794. bindNamedAction(link, data.action);
  1795. } else {
  1796. bindLink(link, ('dest' in data) ? data.dest : null);
  1797. }
  1798. }
  1799. }
  1800. if (!self.div) {
  1801. var annotationLayerDiv = document.createElement('div');
  1802. annotationLayerDiv.className = 'annotationLayer';
  1803. self.pageDiv.appendChild(annotationLayerDiv);
  1804. self.div = annotationLayerDiv;
  1805. }
  1806. self.div.appendChild(element);
  1807. }
  1808. }
  1809. });
  1810. },
  1811. hide: function () {
  1812. if (!this.div) {
  1813. return;
  1814. }
  1815. this.div.setAttribute('hidden', 'true');
  1816. }
  1817. };
  1818. return AnnotationsLayerBuilder;
  1819. })();
  1820. /**
  1821. * @constructor
  1822. * @implements IPDFAnnotationsLayerFactory
  1823. */
  1824. function DefaultAnnotationsLayerFactory() {}
  1825. DefaultAnnotationsLayerFactory.prototype = {
  1826. /**
  1827. * @param {HTMLDivElement} pageDiv
  1828. * @param {PDFPage} pdfPage
  1829. * @returns {AnnotationsLayerBuilder}
  1830. */
  1831. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  1832. return new AnnotationsLayerBuilder({
  1833. pageDiv: pageDiv,
  1834. pdfPage: pdfPage,
  1835. linkService: new SimpleLinkService(),
  1836. });
  1837. }
  1838. };
  1839. /**
  1840. * @typedef {Object} PDFViewerOptions
  1841. * @property {HTMLDivElement} container - The container for the viewer element.
  1842. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  1843. * @property {IPDFLinkService} linkService - The navigation/linking service.
  1844. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  1845. * queue object.
  1846. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  1847. * around the pages. The default is false.
  1848. */
  1849. /**
  1850. * Simple viewer control to display PDF content/pages.
  1851. * @class
  1852. * @implements {IRenderableView}
  1853. */
  1854. var PDFViewer = (function pdfViewer() {
  1855. function PDFPageViewBuffer(size) {
  1856. var data = [];
  1857. this.push = function cachePush(view) {
  1858. var i = data.indexOf(view);
  1859. if (i >= 0) {
  1860. data.splice(i, 1);
  1861. }
  1862. data.push(view);
  1863. if (data.length > size) {
  1864. data.shift().destroy();
  1865. }
  1866. };
  1867. this.resize = function (newSize) {
  1868. size = newSize;
  1869. while (data.length > size) {
  1870. data.shift().destroy();
  1871. }
  1872. };
  1873. }
  1874. function isSameScale(oldScale, newScale) {
  1875. if (newScale === oldScale) {
  1876. return true;
  1877. }
  1878. if (Math.abs(newScale - oldScale) < 1e-15) {
  1879. // Prevent unnecessary re-rendering of all pages when the scale
  1880. // changes only because of limited numerical precision.
  1881. return true;
  1882. }
  1883. return false;
  1884. }
  1885. /**
  1886. * @constructs PDFViewer
  1887. * @param {PDFViewerOptions} options
  1888. */
  1889. function PDFViewer(options) {
  1890. this.container = options.container;
  1891. this.viewer = options.viewer || options.container.firstElementChild;
  1892. this.linkService = options.linkService || new SimpleLinkService();
  1893. this.removePageBorders = options.removePageBorders || false;
  1894. this.defaultRenderingQueue = !options.renderingQueue;
  1895. if (this.defaultRenderingQueue) {
  1896. // Custom rendering queue is not specified, using default one
  1897. this.renderingQueue = new PDFRenderingQueue();
  1898. this.renderingQueue.setViewer(this);
  1899. } else {
  1900. this.renderingQueue = options.renderingQueue;
  1901. }
  1902. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  1903. this.updateInProgress = false;
  1904. this.presentationModeState = PresentationModeState.UNKNOWN;
  1905. this._resetView();
  1906. if (this.removePageBorders) {
  1907. this.viewer.classList.add('removePageBorders');
  1908. }
  1909. }
  1910. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  1911. get pagesCount() {
  1912. return this._pages.length;
  1913. },
  1914. getPageView: function (index) {
  1915. return this._pages[index];
  1916. },
  1917. get currentPageNumber() {
  1918. return this._currentPageNumber;
  1919. },
  1920. set currentPageNumber(val) {
  1921. if (!this.pdfDocument) {
  1922. this._currentPageNumber = val;
  1923. return;
  1924. }
  1925. var event = document.createEvent('UIEvents');
  1926. event.initUIEvent('pagechange', true, true, window, 0);
  1927. event.updateInProgress = this.updateInProgress;
  1928. if (!(0 < val && val <= this.pagesCount)) {
  1929. event.pageNumber = this._currentPageNumber;
  1930. event.previousPageNumber = val;
  1931. this.container.dispatchEvent(event);
  1932. return;
  1933. }
  1934. event.previousPageNumber = this._currentPageNumber;
  1935. this._currentPageNumber = val;
  1936. event.pageNumber = val;
  1937. this.container.dispatchEvent(event);
  1938. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  1939. if (this.updateInProgress) {
  1940. return;
  1941. }
  1942. this.scrollPageIntoView(val);
  1943. },
  1944. /**
  1945. * @returns {number}
  1946. */
  1947. get currentScale() {
  1948. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  1949. DEFAULT_SCALE;
  1950. },
  1951. /**
  1952. * @param {number} val - Scale of the pages in percents.
  1953. */
  1954. set currentScale(val) {
  1955. if (isNaN(val)) {
  1956. throw new Error('Invalid numeric scale');
  1957. }
  1958. if (!this.pdfDocument) {
  1959. this._currentScale = val;
  1960. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  1961. return;
  1962. }
  1963. this._setScale(val, false);
  1964. },
  1965. /**
  1966. * @returns {string}
  1967. */
  1968. get currentScaleValue() {
  1969. return this._currentScaleValue;
  1970. },
  1971. /**
  1972. * @param val - The scale of the pages (in percent or predefined value).
  1973. */
  1974. set currentScaleValue(val) {
  1975. if (!this.pdfDocument) {
  1976. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  1977. this._currentScaleValue = val;
  1978. return;
  1979. }
  1980. this._setScale(val, false);
  1981. },
  1982. /**
  1983. * @returns {number}
  1984. */
  1985. get pagesRotation() {
  1986. return this._pagesRotation;
  1987. },
  1988. /**
  1989. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  1990. */
  1991. set pagesRotation(rotation) {
  1992. this._pagesRotation = rotation;
  1993. for (var i = 0, l = this._pages.length; i < l; i++) {
  1994. var pageView = this._pages[i];
  1995. pageView.update(pageView.scale, rotation);
  1996. }
  1997. this._setScale(this._currentScaleValue, true);
  1998. if (this.defaultRenderingQueue) {
  1999. this.update();
  2000. }
  2001. },
  2002. /**
  2003. * @param pdfDocument {PDFDocument}
  2004. */
  2005. setDocument: function (pdfDocument) {
  2006. if (this.pdfDocument) {
  2007. this._resetView();
  2008. }
  2009. this.pdfDocument = pdfDocument;
  2010. if (!pdfDocument) {
  2011. return;
  2012. }
  2013. var pagesCount = pdfDocument.numPages;
  2014. var self = this;
  2015. var resolvePagesPromise;
  2016. var pagesPromise = new Promise(function (resolve) {
  2017. resolvePagesPromise = resolve;
  2018. });
  2019. this.pagesPromise = pagesPromise;
  2020. pagesPromise.then(function () {
  2021. var event = document.createEvent('CustomEvent');
  2022. event.initCustomEvent('pagesloaded', true, true, {
  2023. pagesCount: pagesCount
  2024. });
  2025. self.container.dispatchEvent(event);
  2026. });
  2027. var isOnePageRenderedResolved = false;
  2028. var resolveOnePageRendered = null;
  2029. var onePageRendered = new Promise(function (resolve) {
  2030. resolveOnePageRendered = resolve;
  2031. });
  2032. this.onePageRendered = onePageRendered;
  2033. var bindOnAfterAndBeforeDraw = function (pageView) {
  2034. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  2035. // Add the page to the buffer at the start of drawing. That way it can
  2036. // be evicted from the buffer and destroyed even if we pause its
  2037. // rendering.
  2038. self._buffer.push(this);
  2039. };
  2040. // when page is painted, using the image as thumbnail base
  2041. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  2042. if (!isOnePageRenderedResolved) {
  2043. isOnePageRenderedResolved = true;
  2044. resolveOnePageRendered();
  2045. }
  2046. };
  2047. };
  2048. var firstPagePromise = pdfDocument.getPage(1);
  2049. this.firstPagePromise = firstPagePromise;
  2050. // Fetch a single page so we can get a viewport that will be the default
  2051. // viewport for all pages
  2052. return firstPagePromise.then(function(pdfPage) {
  2053. var scale = this.currentScale;
  2054. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  2055. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  2056. var textLayerFactory = null;
  2057. if (!PDFJS.disableTextLayer) {
  2058. textLayerFactory = this;
  2059. }
  2060. var pageView = new PDFPageView({
  2061. container: this.viewer,
  2062. id: pageNum,
  2063. scale: scale,
  2064. defaultViewport: viewport.clone(),
  2065. renderingQueue: this.renderingQueue,
  2066. textLayerFactory: textLayerFactory,
  2067. annotationsLayerFactory: this
  2068. });
  2069. bindOnAfterAndBeforeDraw(pageView);
  2070. this._pages.push(pageView);
  2071. }
  2072. var linkService = this.linkService;
  2073. // Fetch all the pages since the viewport is needed before printing
  2074. // starts to create the correct size canvas. Wait until one page is
  2075. // rendered so we don't tie up too many resources early on.
  2076. onePageRendered.then(function () {
  2077. if (!PDFJS.disableAutoFetch) {
  2078. var getPagesLeft = pagesCount;
  2079. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  2080. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  2081. var pageView = self._pages[pageNum - 1];
  2082. if (!pageView.pdfPage) {
  2083. pageView.setPdfPage(pdfPage);
  2084. }
  2085. linkService.cachePageRef(pageNum, pdfPage.ref);
  2086. getPagesLeft--;
  2087. if (!getPagesLeft) {
  2088. resolvePagesPromise();
  2089. }
  2090. }.bind(null, pageNum));
  2091. }
  2092. } else {
  2093. // XXX: Printing is semi-broken with auto fetch disabled.
  2094. resolvePagesPromise();
  2095. }
  2096. });
  2097. var event = document.createEvent('CustomEvent');
  2098. event.initCustomEvent('pagesinit', true, true, null);
  2099. self.container.dispatchEvent(event);
  2100. if (this.defaultRenderingQueue) {
  2101. this.update();
  2102. }
  2103. if (this.findController) {
  2104. this.findController.resolveFirstPage();
  2105. }
  2106. }.bind(this));
  2107. },
  2108. _resetView: function () {
  2109. this._pages = [];
  2110. this._currentPageNumber = 1;
  2111. this._currentScale = UNKNOWN_SCALE;
  2112. this._currentScaleValue = null;
  2113. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  2114. this._location = null;
  2115. this._pagesRotation = 0;
  2116. this._pagesRequests = [];
  2117. var container = this.viewer;
  2118. while (container.hasChildNodes()) {
  2119. container.removeChild(container.lastChild);
  2120. }
  2121. },
  2122. _scrollUpdate: function PDFViewer_scrollUpdate() {
  2123. if (this.pagesCount === 0) {
  2124. return;
  2125. }
  2126. this.update();
  2127. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2128. this._pages[i].updatePosition();
  2129. }
  2130. },
  2131. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  2132. newScale, newValue, preset) {
  2133. var event = document.createEvent('UIEvents');
  2134. event.initUIEvent('scalechange', true, true, window, 0);
  2135. event.scale = newScale;
  2136. if (preset) {
  2137. event.presetValue = newValue;
  2138. }
  2139. this.container.dispatchEvent(event);
  2140. },
  2141. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  2142. newScale, newValue, noScroll, preset) {
  2143. this._currentScaleValue = newValue;
  2144. if (isSameScale(this._currentScale, newScale)) {
  2145. if (preset) {
  2146. this._setScaleDispatchEvent(newScale, newValue, true);
  2147. }
  2148. return;
  2149. }
  2150. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2151. this._pages[i].update(newScale);
  2152. }
  2153. this._currentScale = newScale;
  2154. if (!noScroll) {
  2155. var page = this._currentPageNumber, dest;
  2156. if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
  2157. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  2158. page = this._location.pageNumber;
  2159. dest = [null, { name: 'XYZ' }, this._location.left,
  2160. this._location.top, null];
  2161. }
  2162. this.scrollPageIntoView(page, dest);
  2163. }
  2164. this._setScaleDispatchEvent(newScale, newValue, preset);
  2165. if (this.defaultRenderingQueue) {
  2166. this.update();
  2167. }
  2168. },
  2169. _setScale: function pdfViewer_setScale(value, noScroll) {
  2170. var scale = parseFloat(value);
  2171. if (scale > 0) {
  2172. this._setScaleUpdatePages(scale, value, noScroll, false);
  2173. } else {
  2174. var currentPage = this._pages[this._currentPageNumber - 1];
  2175. if (!currentPage) {
  2176. return;
  2177. }
  2178. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2179. 0 : SCROLLBAR_PADDING;
  2180. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2181. 0 : VERTICAL_PADDING;
  2182. var pageWidthScale = (this.container.clientWidth - hPadding) /
  2183. currentPage.width * currentPage.scale;
  2184. var pageHeightScale = (this.container.clientHeight - vPadding) /
  2185. currentPage.height * currentPage.scale;
  2186. switch (value) {
  2187. case 'page-actual':
  2188. scale = 1;
  2189. break;
  2190. case 'page-width':
  2191. scale = pageWidthScale;
  2192. break;
  2193. case 'page-height':
  2194. scale = pageHeightScale;
  2195. break;
  2196. case 'page-fit':
  2197. scale = Math.min(pageWidthScale, pageHeightScale);
  2198. break;
  2199. case 'auto':
  2200. var isLandscape = (currentPage.width > currentPage.height);
  2201. // For pages in landscape mode, fit the page height to the viewer
  2202. // *unless* the page would thus become too wide to fit horizontally.
  2203. var horizontalScale = isLandscape ?
  2204. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  2205. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  2206. break;
  2207. default:
  2208. console.error('pdfViewSetScale: \'' + value +
  2209. '\' is an unknown zoom value.');
  2210. return;
  2211. }
  2212. this._setScaleUpdatePages(scale, value, noScroll, true);
  2213. }
  2214. },
  2215. /**
  2216. * Scrolls page into view.
  2217. * @param {number} pageNumber
  2218. * @param {Array} dest - (optional) original PDF destination array:
  2219. * <page-ref> </XYZ|FitXXX> <args..>
  2220. */
  2221. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  2222. dest) {
  2223. if (!this.pdfDocument) {
  2224. return;
  2225. }
  2226. var pageView = this._pages[pageNumber - 1];
  2227. if (this.isInPresentationMode) {
  2228. if (this._currentPageNumber !== pageView.id) {
  2229. // Avoid breaking getVisiblePages in presentation mode.
  2230. this.currentPageNumber = pageView.id;
  2231. return;
  2232. }
  2233. dest = null;
  2234. // Fixes the case when PDF has different page sizes.
  2235. this._setScale(this._currentScaleValue, true);
  2236. }
  2237. if (!dest) {
  2238. scrollIntoView(pageView.div);
  2239. return;
  2240. }
  2241. var x = 0, y = 0;
  2242. var width = 0, height = 0, widthScale, heightScale;
  2243. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  2244. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  2245. pageView.scale / CSS_UNITS;
  2246. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  2247. pageView.scale / CSS_UNITS;
  2248. var scale = 0;
  2249. switch (dest[1].name) {
  2250. case 'XYZ':
  2251. x = dest[2];
  2252. y = dest[3];
  2253. scale = dest[4];
  2254. // If x and/or y coordinates are not supplied, default to
  2255. // _top_ left of the page (not the obvious bottom left,
  2256. // since aligning the bottom of the intended page with the
  2257. // top of the window is rarely helpful).
  2258. x = x !== null ? x : 0;
  2259. y = y !== null ? y : pageHeight;
  2260. break;
  2261. case 'Fit':
  2262. case 'FitB':
  2263. scale = 'page-fit';
  2264. break;
  2265. case 'FitH':
  2266. case 'FitBH':
  2267. y = dest[2];
  2268. scale = 'page-width';
  2269. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  2270. // parameter should maintain the position relative to the new page.
  2271. if (y === null && this._location) {
  2272. x = this._location.left;
  2273. y = this._location.top;
  2274. }
  2275. break;
  2276. case 'FitV':
  2277. case 'FitBV':
  2278. x = dest[2];
  2279. width = pageWidth;
  2280. height = pageHeight;
  2281. scale = 'page-height';
  2282. break;
  2283. case 'FitR':
  2284. x = dest[2];
  2285. y = dest[3];
  2286. width = dest[4] - x;
  2287. height = dest[5] - y;
  2288. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  2289. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  2290. widthScale = (this.container.clientWidth - hPadding) /
  2291. width / CSS_UNITS;
  2292. heightScale = (this.container.clientHeight - vPadding) /
  2293. height / CSS_UNITS;
  2294. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  2295. break;
  2296. default:
  2297. return;
  2298. }
  2299. if (scale && scale !== this._currentScale) {
  2300. this.currentScaleValue = scale;
  2301. } else if (this._currentScale === UNKNOWN_SCALE) {
  2302. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  2303. }
  2304. if (scale === 'page-fit' && !dest[4]) {
  2305. scrollIntoView(pageView.div);
  2306. return;
  2307. }
  2308. var boundingRect = [
  2309. pageView.viewport.convertToViewportPoint(x, y),
  2310. pageView.viewport.convertToViewportPoint(x + width, y + height)
  2311. ];
  2312. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  2313. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  2314. scrollIntoView(pageView.div, { left: left, top: top });
  2315. },
  2316. _updateLocation: function (firstPage) {
  2317. var currentScale = this._currentScale;
  2318. var currentScaleValue = this._currentScaleValue;
  2319. var normalizedScaleValue =
  2320. parseFloat(currentScaleValue) === currentScale ?
  2321. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  2322. var pageNumber = firstPage.id;
  2323. var pdfOpenParams = '#page=' + pageNumber;
  2324. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  2325. var currentPageView = this._pages[pageNumber - 1];
  2326. var container = this.container;
  2327. var topLeft = currentPageView.getPagePoint(
  2328. (container.scrollLeft - firstPage.x),
  2329. (container.scrollTop - firstPage.y));
  2330. var intLeft = Math.round(topLeft[0]);
  2331. var intTop = Math.round(topLeft[1]);
  2332. pdfOpenParams += ',' + intLeft + ',' + intTop;
  2333. this._location = {
  2334. pageNumber: pageNumber,
  2335. scale: normalizedScaleValue,
  2336. top: intTop,
  2337. left: intLeft,
  2338. pdfOpenParams: pdfOpenParams
  2339. };
  2340. },
  2341. update: function PDFViewer_update() {
  2342. var visible = this._getVisiblePages();
  2343. var visiblePages = visible.views;
  2344. if (visiblePages.length === 0) {
  2345. return;
  2346. }
  2347. this.updateInProgress = true;
  2348. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  2349. 2 * visiblePages.length + 1);
  2350. this._buffer.resize(suggestedCacheSize);
  2351. this.renderingQueue.renderHighestPriority(visible);
  2352. var currentId = this._currentPageNumber;
  2353. var firstPage = visible.first;
  2354. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  2355. i < ii; ++i) {
  2356. var page = visiblePages[i];
  2357. if (page.percent < 100) {
  2358. break;
  2359. }
  2360. if (page.id === currentId) {
  2361. stillFullyVisible = true;
  2362. break;
  2363. }
  2364. }
  2365. if (!stillFullyVisible) {
  2366. currentId = visiblePages[0].id;
  2367. }
  2368. if (!this.isInPresentationMode) {
  2369. this.currentPageNumber = currentId;
  2370. }
  2371. this._updateLocation(firstPage);
  2372. this.updateInProgress = false;
  2373. var event = document.createEvent('UIEvents');
  2374. event.initUIEvent('updateviewarea', true, true, window, 0);
  2375. event.location = this._location;
  2376. this.container.dispatchEvent(event);
  2377. },
  2378. containsElement: function (element) {
  2379. return this.container.contains(element);
  2380. },
  2381. focus: function () {
  2382. this.container.focus();
  2383. },
  2384. get isInPresentationMode() {
  2385. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  2386. },
  2387. get isChangingPresentationMode() {
  2388. return this.presentationModeState === PresentationModeState.CHANGING;
  2389. },
  2390. get isHorizontalScrollbarEnabled() {
  2391. return (this.isInPresentationMode ?
  2392. false : (this.container.scrollWidth > this.container.clientWidth));
  2393. },
  2394. _getVisiblePages: function () {
  2395. if (!this.isInPresentationMode) {
  2396. return getVisibleElements(this.container, this._pages, true);
  2397. } else {
  2398. // The algorithm in getVisibleElements doesn't work in all browsers and
  2399. // configurations when presentation mode is active.
  2400. var visible = [];
  2401. var currentPage = this._pages[this._currentPageNumber - 1];
  2402. visible.push({ id: currentPage.id, view: currentPage });
  2403. return { first: currentPage, last: currentPage, views: visible };
  2404. }
  2405. },
  2406. cleanup: function () {
  2407. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2408. if (this._pages[i] &&
  2409. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  2410. this._pages[i].reset();
  2411. }
  2412. }
  2413. },
  2414. /**
  2415. * @param {PDFPageView} pageView
  2416. * @returns {PDFPage}
  2417. * @private
  2418. */
  2419. _ensurePdfPageLoaded: function (pageView) {
  2420. if (pageView.pdfPage) {
  2421. return Promise.resolve(pageView.pdfPage);
  2422. }
  2423. var pageNumber = pageView.id;
  2424. if (this._pagesRequests[pageNumber]) {
  2425. return this._pagesRequests[pageNumber];
  2426. }
  2427. var promise = this.pdfDocument.getPage(pageNumber).then(
  2428. function (pdfPage) {
  2429. pageView.setPdfPage(pdfPage);
  2430. this._pagesRequests[pageNumber] = null;
  2431. return pdfPage;
  2432. }.bind(this));
  2433. this._pagesRequests[pageNumber] = promise;
  2434. return promise;
  2435. },
  2436. forceRendering: function (currentlyVisiblePages) {
  2437. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  2438. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  2439. this._pages,
  2440. this.scroll.down);
  2441. if (pageView) {
  2442. this._ensurePdfPageLoaded(pageView).then(function () {
  2443. this.renderingQueue.renderView(pageView);
  2444. }.bind(this));
  2445. return true;
  2446. }
  2447. return false;
  2448. },
  2449. getPageTextContent: function (pageIndex) {
  2450. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  2451. return page.getTextContent();
  2452. });
  2453. },
  2454. /**
  2455. * @param {HTMLDivElement} textLayerDiv
  2456. * @param {number} pageIndex
  2457. * @param {PageViewport} viewport
  2458. * @returns {TextLayerBuilder}
  2459. */
  2460. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2461. return new TextLayerBuilder({
  2462. textLayerDiv: textLayerDiv,
  2463. pageIndex: pageIndex,
  2464. viewport: viewport,
  2465. findController: this.isInPresentationMode ? null : this.findController
  2466. });
  2467. },
  2468. /**
  2469. * @param {HTMLDivElement} pageDiv
  2470. * @param {PDFPage} pdfPage
  2471. * @returns {AnnotationsLayerBuilder}
  2472. */
  2473. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  2474. return new AnnotationsLayerBuilder({
  2475. pageDiv: pageDiv,
  2476. pdfPage: pdfPage,
  2477. linkService: this.linkService
  2478. });
  2479. },
  2480. setFindController: function (findController) {
  2481. this.findController = findController;
  2482. },
  2483. };
  2484. return PDFViewer;
  2485. })();
  2486. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  2487. function SimpleLinkService() {}
  2488. SimpleLinkService.prototype = {
  2489. /**
  2490. * @returns {number}
  2491. */
  2492. get page() {
  2493. return 0;
  2494. },
  2495. /**
  2496. * @param {number} value
  2497. */
  2498. set page(value) {},
  2499. /**
  2500. * @param dest - The PDF destination object.
  2501. */
  2502. navigateTo: function (dest) {},
  2503. /**
  2504. * @param dest - The PDF destination object.
  2505. * @returns {string} The hyperlink to the PDF object.
  2506. */
  2507. getDestinationHash: function (dest) {
  2508. return '#';
  2509. },
  2510. /**
  2511. * @param hash - The PDF parameters/hash.
  2512. * @returns {string} The hyperlink to the PDF object.
  2513. */
  2514. getAnchorUrl: function (hash) {
  2515. return '#';
  2516. },
  2517. /**
  2518. * @param {string} hash
  2519. */
  2520. setHash: function (hash) {},
  2521. /**
  2522. * @param {string} action
  2523. */
  2524. executeNamedAction: function (action) {},
  2525. /**
  2526. * @param {number} pageNum - page number.
  2527. * @param {Object} pageRef - reference to the page.
  2528. */
  2529. cachePageRef: function (pageNum, pageRef) {}
  2530. };
  2531. return SimpleLinkService;
  2532. })();
  2533. var PDFHistory = (function () {
  2534. function PDFHistory(options) {
  2535. this.linkService = options.linkService;
  2536. this.initialized = false;
  2537. this.initialDestination = null;
  2538. this.initialBookmark = null;
  2539. }
  2540. PDFHistory.prototype = {
  2541. /**
  2542. * @param {string} fingerprint
  2543. * @param {IPDFLinkService} linkService
  2544. */
  2545. initialize: function pdfHistoryInitialize(fingerprint) {
  2546. this.initialized = true;
  2547. this.reInitialized = false;
  2548. this.allowHashChange = true;
  2549. this.historyUnlocked = true;
  2550. this.isViewerInPresentationMode = false;
  2551. this.previousHash = window.location.hash.substring(1);
  2552. this.currentBookmark = '';
  2553. this.currentPage = 0;
  2554. this.updatePreviousBookmark = false;
  2555. this.previousBookmark = '';
  2556. this.previousPage = 0;
  2557. this.nextHashParam = '';
  2558. this.fingerprint = fingerprint;
  2559. this.currentUid = this.uid = 0;
  2560. this.current = {};
  2561. var state = window.history.state;
  2562. if (this._isStateObjectDefined(state)) {
  2563. // This corresponds to navigating back to the document
  2564. // from another page in the browser history.
  2565. if (state.target.dest) {
  2566. this.initialDestination = state.target.dest;
  2567. } else {
  2568. this.initialBookmark = state.target.hash;
  2569. }
  2570. this.currentUid = state.uid;
  2571. this.uid = state.uid + 1;
  2572. this.current = state.target;
  2573. } else {
  2574. // This corresponds to the loading of a new document.
  2575. if (state && state.fingerprint &&
  2576. this.fingerprint !== state.fingerprint) {
  2577. // Reinitialize the browsing history when a new document
  2578. // is opened in the web viewer.
  2579. this.reInitialized = true;
  2580. }
  2581. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  2582. }
  2583. var self = this;
  2584. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  2585. if (!self.historyUnlocked) {
  2586. return;
  2587. }
  2588. if (evt.state) {
  2589. // Move back/forward in the history.
  2590. self._goTo(evt.state);
  2591. return;
  2592. }
  2593. // If the state is not set, then the user tried to navigate to a
  2594. // different hash by manually editing the URL and pressing Enter, or by
  2595. // clicking on an in-page link (e.g. the "current view" link).
  2596. // Save the current view state to the browser history.
  2597. // Note: In Firefox, history.null could also be null after an in-page
  2598. // navigation to the same URL, and without dispatching the popstate
  2599. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  2600. if (self.uid === 0) {
  2601. // Replace the previous state if it was not explicitly set.
  2602. var previousParams = (self.previousHash && self.currentBookmark &&
  2603. self.previousHash !== self.currentBookmark) ?
  2604. {hash: self.currentBookmark, page: self.currentPage} :
  2605. {page: 1};
  2606. replacePreviousHistoryState(previousParams, function() {
  2607. updateHistoryWithCurrentHash();
  2608. });
  2609. } else {
  2610. updateHistoryWithCurrentHash();
  2611. }
  2612. }, false);
  2613. function updateHistoryWithCurrentHash() {
  2614. self.previousHash = window.location.hash.slice(1);
  2615. self._pushToHistory({hash: self.previousHash}, false, true);
  2616. self._updatePreviousBookmark();
  2617. }
  2618. function replacePreviousHistoryState(params, callback) {
  2619. // To modify the previous history entry, the following happens:
  2620. // 1. history.back()
  2621. // 2. _pushToHistory, which calls history.replaceState( ... )
  2622. // 3. history.forward()
  2623. // Because a navigation via the history API does not immediately update
  2624. // the history state, the popstate event is used for synchronization.
  2625. self.historyUnlocked = false;
  2626. // Suppress the hashchange event to avoid side effects caused by
  2627. // navigating back and forward.
  2628. self.allowHashChange = false;
  2629. window.addEventListener('popstate', rewriteHistoryAfterBack);
  2630. history.back();
  2631. function rewriteHistoryAfterBack() {
  2632. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  2633. window.addEventListener('popstate', rewriteHistoryAfterForward);
  2634. self._pushToHistory(params, false, true);
  2635. history.forward();
  2636. }
  2637. function rewriteHistoryAfterForward() {
  2638. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  2639. self.allowHashChange = true;
  2640. self.historyUnlocked = true;
  2641. callback();
  2642. }
  2643. }
  2644. function pdfHistoryBeforeUnload() {
  2645. var previousParams = self._getPreviousParams(null, true);
  2646. if (previousParams) {
  2647. var replacePrevious = (!self.current.dest &&
  2648. self.current.hash !== self.previousHash);
  2649. self._pushToHistory(previousParams, false, replacePrevious);
  2650. self._updatePreviousBookmark();
  2651. }
  2652. // Remove the event listener when navigating away from the document,
  2653. // since 'beforeunload' prevents Firefox from caching the document.
  2654. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  2655. false);
  2656. }
  2657. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2658. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  2659. // If the entire viewer (including the PDF file) is cached in
  2660. // the browser, we need to reattach the 'beforeunload' event listener
  2661. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  2662. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2663. }, false);
  2664. window.addEventListener('presentationmodechanged', function(e) {
  2665. self.isViewerInPresentationMode = !!e.detail.active;
  2666. });
  2667. },
  2668. clearHistoryState: function pdfHistory_clearHistoryState() {
  2669. this._pushOrReplaceState(null, true);
  2670. },
  2671. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  2672. return (state && state.uid >= 0 &&
  2673. state.fingerprint && this.fingerprint === state.fingerprint &&
  2674. state.target && state.target.hash) ? true : false;
  2675. },
  2676. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  2677. replace) {
  2678. if (replace) {
  2679. window.history.replaceState(stateObj, '');
  2680. } else {
  2681. window.history.pushState(stateObj, '');
  2682. }
  2683. },
  2684. get isHashChangeUnlocked() {
  2685. if (!this.initialized) {
  2686. return true;
  2687. }
  2688. return this.allowHashChange;
  2689. },
  2690. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  2691. if (this.updatePreviousBookmark &&
  2692. this.currentBookmark && this.currentPage) {
  2693. this.previousBookmark = this.currentBookmark;
  2694. this.previousPage = this.currentPage;
  2695. this.updatePreviousBookmark = false;
  2696. }
  2697. },
  2698. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  2699. pageNum) {
  2700. if (this.initialized) {
  2701. this.currentBookmark = bookmark.substring(1);
  2702. this.currentPage = pageNum | 0;
  2703. this._updatePreviousBookmark();
  2704. }
  2705. },
  2706. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  2707. if (this.initialized) {
  2708. this.nextHashParam = param;
  2709. }
  2710. },
  2711. push: function pdfHistoryPush(params, isInitialBookmark) {
  2712. if (!(this.initialized && this.historyUnlocked)) {
  2713. return;
  2714. }
  2715. if (params.dest && !params.hash) {
  2716. params.hash = (this.current.hash && this.current.dest &&
  2717. this.current.dest === params.dest) ?
  2718. this.current.hash :
  2719. this.linkService.getDestinationHash(params.dest).split('#')[1];
  2720. }
  2721. if (params.page) {
  2722. params.page |= 0;
  2723. }
  2724. if (isInitialBookmark) {
  2725. var target = window.history.state.target;
  2726. if (!target) {
  2727. // Invoked when the user specifies an initial bookmark,
  2728. // thus setting initialBookmark, when the document is loaded.
  2729. this._pushToHistory(params, false);
  2730. this.previousHash = window.location.hash.substring(1);
  2731. }
  2732. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  2733. if (target) {
  2734. // If the current document is reloaded,
  2735. // avoid creating duplicate entries in the history.
  2736. this._updatePreviousBookmark();
  2737. }
  2738. return;
  2739. }
  2740. if (this.nextHashParam) {
  2741. if (this.nextHashParam === params.hash) {
  2742. this.nextHashParam = null;
  2743. this.updatePreviousBookmark = true;
  2744. return;
  2745. } else {
  2746. this.nextHashParam = null;
  2747. }
  2748. }
  2749. if (params.hash) {
  2750. if (this.current.hash) {
  2751. if (this.current.hash !== params.hash) {
  2752. this._pushToHistory(params, true);
  2753. } else {
  2754. if (!this.current.page && params.page) {
  2755. this._pushToHistory(params, false, true);
  2756. }
  2757. this.updatePreviousBookmark = true;
  2758. }
  2759. } else {
  2760. this._pushToHistory(params, true);
  2761. }
  2762. } else if (this.current.page && params.page &&
  2763. this.current.page !== params.page) {
  2764. this._pushToHistory(params, true);
  2765. }
  2766. },
  2767. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  2768. beforeUnload) {
  2769. if (!(this.currentBookmark && this.currentPage)) {
  2770. return null;
  2771. } else if (this.updatePreviousBookmark) {
  2772. this.updatePreviousBookmark = false;
  2773. }
  2774. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  2775. // Prevent the history from getting stuck in the current state,
  2776. // effectively preventing the user from going back/forward in
  2777. // the history.
  2778. //
  2779. // This happens if the current position in the document didn't change
  2780. // when the history was previously updated. The reasons for this are
  2781. // either:
  2782. // 1. The current zoom value is such that the document does not need to,
  2783. // or cannot, be scrolled to display the destination.
  2784. // 2. The previous destination is broken, and doesn't actally point to a
  2785. // position within the document.
  2786. // (This is either due to a bad PDF generator, or the user making a
  2787. // mistake when entering a destination in the hash parameters.)
  2788. return null;
  2789. }
  2790. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  2791. if (this.previousBookmark === this.currentBookmark) {
  2792. return null;
  2793. }
  2794. } else if (this.current.page || onlyCheckPage) {
  2795. if (this.previousPage === this.currentPage) {
  2796. return null;
  2797. }
  2798. } else {
  2799. return null;
  2800. }
  2801. var params = {hash: this.currentBookmark, page: this.currentPage};
  2802. if (this.isViewerInPresentationMode) {
  2803. params.hash = null;
  2804. }
  2805. return params;
  2806. },
  2807. _stateObj: function pdfHistory_stateObj(params) {
  2808. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  2809. },
  2810. _pushToHistory: function pdfHistory_pushToHistory(params,
  2811. addPrevious, overwrite) {
  2812. if (!this.initialized) {
  2813. return;
  2814. }
  2815. if (!params.hash && params.page) {
  2816. params.hash = ('page=' + params.page);
  2817. }
  2818. if (addPrevious && !overwrite) {
  2819. var previousParams = this._getPreviousParams();
  2820. if (previousParams) {
  2821. var replacePrevious = (!this.current.dest &&
  2822. this.current.hash !== this.previousHash);
  2823. this._pushToHistory(previousParams, false, replacePrevious);
  2824. }
  2825. }
  2826. this._pushOrReplaceState(this._stateObj(params),
  2827. (overwrite || this.uid === 0));
  2828. this.currentUid = this.uid++;
  2829. this.current = params;
  2830. this.updatePreviousBookmark = true;
  2831. },
  2832. _goTo: function pdfHistory_goTo(state) {
  2833. if (!(this.initialized && this.historyUnlocked &&
  2834. this._isStateObjectDefined(state))) {
  2835. return;
  2836. }
  2837. if (!this.reInitialized && state.uid < this.currentUid) {
  2838. var previousParams = this._getPreviousParams(true);
  2839. if (previousParams) {
  2840. this._pushToHistory(this.current, false);
  2841. this._pushToHistory(previousParams, false);
  2842. this.currentUid = state.uid;
  2843. window.history.back();
  2844. return;
  2845. }
  2846. }
  2847. this.historyUnlocked = false;
  2848. if (state.target.dest) {
  2849. this.linkService.navigateTo(state.target.dest);
  2850. } else {
  2851. this.linkService.setHash(state.target.hash);
  2852. }
  2853. this.currentUid = state.uid;
  2854. if (state.uid > this.uid) {
  2855. this.uid = state.uid;
  2856. }
  2857. this.current = state.target;
  2858. this.updatePreviousBookmark = true;
  2859. var currentHash = window.location.hash.substring(1);
  2860. if (this.previousHash !== currentHash) {
  2861. this.allowHashChange = false;
  2862. }
  2863. this.previousHash = currentHash;
  2864. this.historyUnlocked = true;
  2865. },
  2866. back: function pdfHistoryBack() {
  2867. this.go(-1);
  2868. },
  2869. forward: function pdfHistoryForward() {
  2870. this.go(1);
  2871. },
  2872. go: function pdfHistoryGo(direction) {
  2873. if (this.initialized && this.historyUnlocked) {
  2874. var state = window.history.state;
  2875. if (direction === -1 && state && state.uid > 0) {
  2876. window.history.back();
  2877. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  2878. window.history.forward();
  2879. }
  2880. }
  2881. }
  2882. };
  2883. return PDFHistory;
  2884. })();
  2885. PDFJS.PDFViewer = PDFViewer;
  2886. PDFJS.PDFPageView = PDFPageView;
  2887. PDFJS.PDFLinkService = PDFLinkService;
  2888. PDFJS.TextLayerBuilder = TextLayerBuilder;
  2889. PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2890. PDFJS.AnnotationsLayerBuilder = AnnotationsLayerBuilder;
  2891. PDFJS.DefaultAnnotationsLayerFactory = DefaultAnnotationsLayerFactory;
  2892. PDFJS.PDFHistory = PDFHistory;
  2893. PDFJS.getFileName = getFileName;
  2894. PDFJS.ProgressBar = ProgressBar;
  2895. }).call((typeof window === 'undefined') ? this : window);