pdfRenderer.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /* eslint-disable
  2. handle-callback-err,
  3. max-len,
  4. new-cap,
  5. no-return-assign,
  6. no-undef,
  7. no-unused-vars,
  8. */
  9. // TODO: This file was created by bulk-decaffeinate.
  10. // Fix any style issues and re-enable lint.
  11. /*
  12. * decaffeinate suggestions:
  13. * DS101: Remove unnecessary use of Array.from
  14. * DS102: Remove unnecessary code created because of implicit returns
  15. * DS103: Rewrite code to no longer use __guard__
  16. * DS205: Consider reworking code to avoid use of IIFEs
  17. * DS206: Consider reworking classes to avoid initClass
  18. * DS207: Consider shorter variations of null checks
  19. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  20. */
  21. define(['base', './pdfJsLoader'], (App, PDFJS) =>
  22. // App = angular.module 'PDFRenderer', ['pdfAnnotations', 'pdfTextLayer']
  23. App.factory('PDFRenderer', function(
  24. $q,
  25. $timeout,
  26. pdfAnnotations,
  27. pdfTextLayer,
  28. pdfSpinner
  29. ) {
  30. let PDFRenderer
  31. return (PDFRenderer = (function() {
  32. PDFRenderer = class PDFRenderer {
  33. static initClass() {
  34. this.prototype.JOB_QUEUE_INTERVAL = 25
  35. this.prototype.PAGE_LOAD_TIMEOUT = 60 * 1000
  36. this.prototype.INDICATOR_DELAY1 = 100 // time to delay before showing the indicator
  37. this.prototype.INDICATOR_DELAY2 = 250 // time until the indicator starts animating
  38. this.prototype.TEXTLAYER_TIMEOUT = 100
  39. }
  40. constructor(url, options) {
  41. // set up external character mappings - needed for Japanese etc
  42. this.url = url
  43. this.options = options
  44. this.scale = this.options.scale || 1
  45. let disableFontFace
  46. if (
  47. __guard__(
  48. window.location != null ? window.location.search : undefined,
  49. x => x.indexOf('disable-font-face=true')
  50. ) >= 0
  51. ) {
  52. disableFontFace = true
  53. } else {
  54. disableFontFace = false
  55. }
  56. this.pdfjs = PDFJS.getDocument({
  57. url: this.url,
  58. cMapUrl: window.pdfCMapsPath,
  59. cMapPacked: true,
  60. disableFontFace,
  61. // Enable fetching with Range headers to restrict individual
  62. // requests to 128kb.
  63. // To do this correctly we must:
  64. // a) disable auto-fetching of the whole file upfront
  65. // b) disable streaming (which in this context means streaming of
  66. // the response into memory). This isn't supported when using
  67. // Range headers, but shouldn't be a problem since we are already
  68. // limiting individual response size through chunked range
  69. // requests
  70. rangeChunkSize: 128 * 1024,
  71. disableAutoFetch: !!this.options.disableAutoFetch,
  72. disableStream: !!this.options.disableAutoFetch
  73. })
  74. this.pdfjs.onProgress = this.options.progressCallback
  75. this.document = $q.when(this.pdfjs)
  76. this.navigateFn = this.options.navigateFn
  77. this.spinner = new pdfSpinner()
  78. this.resetState()
  79. this.document.then(pdfDocument => {
  80. return pdfDocument.getDownloadInfo().then(() => {
  81. return this.options.loadedCallback()
  82. })
  83. })
  84. this.errorCallback = this.options.errorCallback
  85. this.pageSizeChangeCallback = this.options.pageSizeChangeCallback
  86. this.pdfjs.promise.catch(exception => {
  87. // error getting document
  88. return this.errorCallback(exception)
  89. })
  90. }
  91. resetState() {
  92. this.renderQueue = []
  93. if (this.queueTimer != null) {
  94. clearTimeout(this.queueTimer)
  95. }
  96. // clear any existing timers, render tasks
  97. for (let timer of Array.from(this.spinTimer || [])) {
  98. clearTimeout(timer)
  99. }
  100. for (let page of Array.from(this.pageState || [])) {
  101. __guard__(page != null ? page.loadTask : undefined, x => x.cancel())
  102. __guard__(page != null ? page.renderTask : undefined, x1 =>
  103. x1.cancel()
  104. )
  105. }
  106. // initialise/reset the state
  107. this.pageState = []
  108. this.spinTimer = [] // timers for starting the spinners (to avoid jitter)
  109. this.spinTimerDone = [] // array of pages where the spinner has activated
  110. return (this.jobs = 0)
  111. }
  112. getNumPages() {
  113. return this.document.then(pdfDocument => pdfDocument.numPages)
  114. }
  115. getPage(pageNum) {
  116. return this.document.then(pdfDocument => pdfDocument.getPage(pageNum))
  117. }
  118. getPdfViewport(pageNum, scale) {
  119. if (scale == null) {
  120. ;({ scale } = this)
  121. }
  122. return this.document.then(pdfDocument => {
  123. return pdfDocument.getPage(pageNum).then(
  124. function(page) {
  125. let viewport
  126. return (viewport = page.getViewport(scale))
  127. },
  128. error => {
  129. return typeof this.errorCallback === 'function'
  130. ? this.errorCallback(error)
  131. : undefined
  132. }
  133. )
  134. })
  135. }
  136. getDestinations() {
  137. return this.document.then(pdfDocument =>
  138. pdfDocument.getDestinations()
  139. )
  140. }
  141. getDestination(dest) {
  142. return this.document.then(
  143. pdfDocument => pdfDocument.getDestination(dest),
  144. error => {
  145. return typeof this.errorCallback === 'function'
  146. ? this.errorCallback(error)
  147. : undefined
  148. }
  149. )
  150. }
  151. getPageIndex(ref) {
  152. return this.document.then(pdfDocument => {
  153. return pdfDocument.getPageIndex(ref).then(
  154. idx => idx,
  155. error => {
  156. return typeof this.errorCallback === 'function'
  157. ? this.errorCallback(error)
  158. : undefined
  159. }
  160. )
  161. })
  162. }
  163. getScale() {
  164. return this.scale
  165. }
  166. setScale(scale) {
  167. this.scale = scale
  168. return this.resetState()
  169. }
  170. triggerRenderQueue(interval) {
  171. if (interval == null) {
  172. interval = this.JOB_QUEUE_INTERVAL
  173. }
  174. if (this.queueTimer != null) {
  175. clearTimeout(this.queueTimer)
  176. }
  177. return (this.queueTimer = setTimeout(() => {
  178. this.queueTimer = null
  179. return this.processRenderQueue()
  180. }, interval))
  181. }
  182. removeCompletedJob(pagenum) {
  183. this.jobs = this.jobs - 1
  184. return this.triggerRenderQueue(0)
  185. }
  186. renderPages(pages) {
  187. if (this.shuttingDown) {
  188. return
  189. }
  190. this.renderQueue = Array.from(pages).map(page => ({
  191. element: page.elementChildren,
  192. pagenum: page.pageNum
  193. }))
  194. return this.triggerRenderQueue()
  195. }
  196. renderPage(page) {
  197. if (this.shuttingDown) {
  198. return
  199. }
  200. const current = {
  201. element: page.elementChildren,
  202. pagenum: page.pageNum
  203. }
  204. this.renderQueue.push(current)
  205. return this.processRenderQueue()
  206. }
  207. getPageDetails(page) {
  208. return [page.element.canvas, page.pagenum]
  209. }
  210. // handle the loading indicators for each page
  211. startIndicators() {
  212. // make an array of the pages in the queue
  213. this.queuedPages = []
  214. for (var page of Array.from(this.renderQueue)) {
  215. this.queuedPages[page.pagenum] = true
  216. }
  217. // clear any unfinished spinner timers on pages that aren't in the queue any more
  218. for (let pagenum in this.spinTimer) {
  219. if (!this.queuedPages[pagenum]) {
  220. clearTimeout(this.spinTimer[pagenum])
  221. delete this.spinTimer[pagenum]
  222. }
  223. }
  224. // add indicators for any new pages in the current queue
  225. return (() => {
  226. const result = []
  227. for (page of Array.from(this.renderQueue)) {
  228. if (
  229. !this.spinTimer[page.pagenum] &&
  230. !this.spinTimerDone[page.pagenum]
  231. ) {
  232. result.push(this.startIndicator(page))
  233. }
  234. }
  235. return result
  236. })()
  237. }
  238. startIndicator(page) {
  239. const [canvas, pagenum] = Array.from(this.getPageDetails(page))
  240. canvas.addClass('pdfng-loading')
  241. return (this.spinTimer[pagenum] = setTimeout(() => {
  242. for (let queuedPage of Array.from(this.renderQueue)) {
  243. if (pagenum === queuedPage.pagenum) {
  244. this.spinner.add(canvas, { static: true })
  245. this.spinTimerDone[pagenum] = true
  246. break
  247. }
  248. }
  249. return delete this.spinTimer[pagenum]
  250. }, this.INDICATOR_DELAY1))
  251. }
  252. updateIndicator(page) {
  253. const [canvas, pagenum] = Array.from(this.getPageDetails(page))
  254. // did the spinner insert itself already?
  255. if (this.spinTimerDone[pagenum]) {
  256. return (this.spinTimer[pagenum] = setTimeout(() => {
  257. this.spinner.start(canvas)
  258. return delete this.spinTimer[pagenum]
  259. }, this.INDICATOR_DELAY2))
  260. } else {
  261. // stop the existing spin timer
  262. clearTimeout(this.spinTimer[pagenum])
  263. // start a new one which will also start spinning
  264. return (this.spinTimer[pagenum] = setTimeout(() => {
  265. this.spinner.add(canvas, { static: true })
  266. this.spinTimerDone[pagenum] = true
  267. return (this.spinTimer[pagenum] = setTimeout(() => {
  268. this.spinner.start(canvas)
  269. return delete this.spinTimer[pagenum]
  270. }, this.INDICATOR_DELAY2))
  271. }, this.INDICATOR_DELAY1))
  272. }
  273. }
  274. clearIndicator(page) {
  275. const [canvas, pagenum] = Array.from(this.getPageDetails(page))
  276. this.spinner.stop(canvas)
  277. clearTimeout(this.spinTimer[pagenum])
  278. delete this.spinTimer[pagenum]
  279. return (this.spinTimerDone[pagenum] = true)
  280. }
  281. // handle the queue of pages to be rendered
  282. processRenderQueue() {
  283. let pageState
  284. if (this.shuttingDown) {
  285. return
  286. }
  287. // mark all pages in the queue as loading
  288. this.startIndicators()
  289. // bail out if there is already a render job running
  290. if (this.jobs > 0) {
  291. return
  292. }
  293. // take the first page in the queue
  294. let page = this.renderQueue.shift()
  295. // check if it is in action already
  296. while (page != null && this.pageState[page.pagenum] != null) {
  297. page = this.renderQueue.shift()
  298. }
  299. if (page == null) {
  300. return
  301. }
  302. const [element, pagenum] = Array.from([page.element, page.pagenum])
  303. this.jobs = this.jobs + 1
  304. // update the spinner to make it spinning (signifies loading has begun)
  305. this.updateIndicator(page)
  306. let timedOut = false
  307. const timer = $timeout(() => {
  308. // page load timed out
  309. if (loadTask.cancelled) {
  310. return
  311. } // return from cancelled page load
  312. __guardMethod__(window.Raven, 'captureMessage', o =>
  313. o.captureMessage(
  314. `pdfng page load timed out after ${this.PAGE_LOAD_TIMEOUT}ms`
  315. )
  316. )
  317. timedOut = true
  318. this.clearIndicator(page)
  319. // @jobs = @jobs - 1
  320. // @triggerRenderQueue(0)
  321. return typeof this.errorCallback === 'function'
  322. ? this.errorCallback('timeout')
  323. : undefined
  324. }, this.PAGE_LOAD_TIMEOUT)
  325. var loadTask = this.getPage(pagenum)
  326. loadTask.cancel = function() {
  327. return (this.cancelled = true)
  328. }
  329. this.pageState[pagenum] = pageState = { loadTask }
  330. return loadTask
  331. .then(pageObject => {
  332. // page load success
  333. $timeout.cancel(timer)
  334. if (loadTask.cancelled) {
  335. return
  336. } // return from cancelled page load
  337. pageState.renderTask = this.doRender(element, pagenum, pageObject)
  338. return pageState.renderTask.then(
  339. () => {
  340. // render task success
  341. this.clearIndicator(page)
  342. pageState.complete = true
  343. delete pageState.renderTask
  344. return this.removeCompletedJob(pagenum)
  345. },
  346. () => {
  347. // render task failed
  348. // could display an error icon
  349. pageState.complete = false
  350. delete pageState.renderTask
  351. return this.removeCompletedJob(pagenum)
  352. }
  353. )
  354. })
  355. .catch(error => {
  356. // page load error
  357. $timeout.cancel(timer)
  358. return this.clearIndicator(page)
  359. })
  360. }
  361. doRender(element, pagenum, page) {
  362. const self = this
  363. const { scale } = this
  364. if (scale == null) {
  365. // scale is undefined, returning
  366. return
  367. }
  368. const canvas = $(
  369. '<canvas class="pdf-canvas pdfng-rendering"></canvas>'
  370. )
  371. // In Windows+IE we must have the canvas in the DOM during
  372. // rendering to see the fonts defined in the DOM. If we try to
  373. // render 'offscreen' then all the text will be sans-serif.
  374. // Previously we rendered offscreen and added in the canvas
  375. // when rendering was complete.
  376. element.canvas.replaceWith(canvas)
  377. const viewport = page.getViewport(scale)
  378. const devicePixelRatio = window.devicePixelRatio || 1
  379. const ctx = canvas[0].getContext('2d')
  380. const backingStoreRatio =
  381. ctx.webkitBackingStorePixelRatio ||
  382. ctx.mozBackingStorePixelRatio ||
  383. ctx.msBackingStorePixelRatio ||
  384. ctx.oBackingStorePixelRatio ||
  385. ctx.backingStorePixelRatio ||
  386. 1
  387. const pixelRatio = devicePixelRatio / backingStoreRatio
  388. const scaledWidth = (Math.floor(viewport.width) * pixelRatio) | 0
  389. const scaledHeight = (Math.floor(viewport.height) * pixelRatio) | 0
  390. const newWidth = Math.floor(viewport.width)
  391. const newHeight = Math.floor(viewport.height)
  392. canvas[0].height = scaledHeight
  393. canvas[0].width = scaledWidth
  394. canvas.height(newHeight + 'px')
  395. canvas.width(newWidth + 'px')
  396. const oldHeight = element.canvas.height()
  397. const oldWidth = element.canvas.width()
  398. if (newHeight !== oldHeight || newWidth !== oldWidth) {
  399. element.canvas.height(newHeight + 'px')
  400. element.canvas.width(newWidth + 'px')
  401. element.container.height(newHeight + 'px')
  402. element.container.width(newWidth + 'px')
  403. if (typeof this.pageSizeChangeCallback === 'function') {
  404. this.pageSizeChangeCallback(pagenum, newHeight - oldHeight)
  405. }
  406. }
  407. const textLayer = new pdfTextLayer({
  408. textLayerDiv: element.text[0],
  409. viewport,
  410. renderer: PDFJS.renderTextLayer
  411. })
  412. const annotationsLayer = new pdfAnnotations({
  413. annotations: element.annotations[0],
  414. viewport,
  415. navigateFn: this.navigateFn
  416. })
  417. const result = page.render({
  418. canvasContext: ctx,
  419. viewport,
  420. transform: [pixelRatio, 0, 0, pixelRatio, 0, 0]
  421. })
  422. const textLayerTimeout = this.TEXTLAYER_TIMEOUT
  423. result
  424. .then(function() {
  425. // page render success
  426. canvas.removeClass('pdfng-rendering')
  427. page.getTextContent({ normalizeWhitespace: true }).then(
  428. function(textContent) {
  429. textLayer.setTextContent(textContent)
  430. return textLayer.render(textLayerTimeout)
  431. },
  432. error =>
  433. typeof self.errorCallback === 'function'
  434. ? self.errorCallback(error)
  435. : undefined
  436. )
  437. return page
  438. .getAnnotations()
  439. .then(
  440. annotations => annotationsLayer.setAnnotations(annotations),
  441. error =>
  442. typeof self.errorCallback === 'function'
  443. ? self.errorCallback(error)
  444. : undefined
  445. )
  446. })
  447. .catch(function(error) {
  448. // page render failed
  449. if (error.name === 'RenderingCancelledException') {
  450. // do nothing when cancelled
  451. } else {
  452. return typeof self.errorCallback === 'function'
  453. ? self.errorCallback(error)
  454. : undefined
  455. }
  456. })
  457. return result
  458. }
  459. destroy() {
  460. this.shuttingDown = true
  461. this.resetState()
  462. return this.pdfjs.then(function(document) {
  463. document.cleanup()
  464. return document.destroy()
  465. })
  466. }
  467. }
  468. PDFRenderer.initClass()
  469. return PDFRenderer
  470. })())
  471. }))
  472. function __guard__(value, transform) {
  473. return typeof value !== 'undefined' && value !== null
  474. ? transform(value)
  475. : undefined
  476. }
  477. function __guardMethod__(obj, methodName, transform) {
  478. if (
  479. typeof obj !== 'undefined' &&
  480. obj !== null &&
  481. typeof obj[methodName] === 'function'
  482. ) {
  483. return transform(obj, methodName)
  484. } else {
  485. return undefined
  486. }
  487. }