pdfRenderer.js 19 KB

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