pdf-js-wrapper.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import { captureMessage } from '../../../infrastructure/error-reporter'
  2. import { generatePdfCachingTransportFactory } from './pdf-caching-transport'
  3. const params = new URLSearchParams(window.location.search)
  4. const disableFontFace = params.get('disable-font-face') === 'true'
  5. const disableStream = process.env.NODE_ENV !== 'test'
  6. const DEFAULT_RANGE_CHUNK_SIZE = 128 * 1024 // 128K chunks
  7. export default class PDFJSWrapper {
  8. constructor(container) {
  9. this.container = container
  10. }
  11. async init() {
  12. const { PDFJS, PDFJSViewer, cMapUrl, imageResourcesPath } = await import(
  13. './pdf-js-versions'
  14. ).then(m => {
  15. return m.default
  16. })
  17. this.PDFJS = PDFJS
  18. this.genPdfCachingTransport = generatePdfCachingTransportFactory(PDFJS)
  19. this.PDFJSViewer = PDFJSViewer
  20. this.cMapUrl = cMapUrl
  21. this.imageResourcesPath = imageResourcesPath
  22. // create the event bus
  23. const eventBus = new PDFJSViewer.EventBus()
  24. // create the link service
  25. const linkService = new PDFJSViewer.PDFLinkService({
  26. eventBus,
  27. externalLinkTarget: 2,
  28. externalLinkRel: 'noopener',
  29. })
  30. // create the localization
  31. // const l10n = new PDFJSViewer.GenericL10n('en-GB') // TODO: locale mapping?
  32. // create the viewer
  33. const viewer = new PDFJSViewer.PDFViewer({
  34. container: this.container,
  35. eventBus,
  36. imageResourcesPath,
  37. linkService,
  38. // l10n, // commented out since it currently breaks `aria-label` rendering in pdf pages
  39. enableScripting: false, // default is false, but set explicitly to be sure
  40. enableXfa: false, // default is false (2021-10-12), but set explicitly to be sure
  41. renderInteractiveForms: false,
  42. maxCanvasPixels: 8192 * 8192, // default is 4096 * 4096, increased for better resolution at high zoom levels
  43. })
  44. linkService.setViewer(viewer)
  45. this.eventBus = eventBus
  46. this.linkService = linkService
  47. this.viewer = viewer
  48. }
  49. // load a document from a URL
  50. loadDocument(url, pdfFile) {
  51. // cancel any previous loading task
  52. if (this.loadDocumentTask) {
  53. this.loadDocumentTask.destroy()
  54. this.loadDocumentTask = undefined
  55. }
  56. return new Promise((resolve, reject) => {
  57. const rangeTransport = this.genPdfCachingTransport(url, pdfFile, reject)
  58. let rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE
  59. if (rangeTransport && pdfFile.size < 2 * DEFAULT_RANGE_CHUNK_SIZE) {
  60. // pdf.js disables the "bulk" download optimization when providing a
  61. // custom range transport. Restore it by bumping the chunk size.
  62. rangeChunkSize = pdfFile.size
  63. }
  64. this.loadDocumentTask = this.PDFJS.getDocument({
  65. url,
  66. cMapUrl: this.cMapUrl,
  67. cMapPacked: true,
  68. disableFontFace,
  69. rangeChunkSize,
  70. disableAutoFetch: true,
  71. disableStream,
  72. textLayerMode: 2, // PDFJSViewer.TextLayerMode.ENABLE,
  73. range: rangeTransport,
  74. })
  75. this.loadDocumentTask.promise
  76. .then(doc => {
  77. if (!this.loadDocumentTask) {
  78. return // ignoring the response since loading task has been aborted
  79. }
  80. const previousDoc = this.viewer.pdfDocument
  81. this.viewer.setDocument(doc)
  82. this.linkService.setDocument(doc)
  83. resolve(doc)
  84. if (previousDoc) {
  85. previousDoc.cleanup().catch(console.error)
  86. previousDoc.destroy()
  87. }
  88. })
  89. .catch(error => {
  90. if (this.loadDocumentTask) {
  91. if (!error || error.name !== 'MissingPDFException') {
  92. captureMessage(`pdf preview error ${error}`)
  93. }
  94. reject(error)
  95. }
  96. })
  97. .finally(() => {
  98. this.loadDocumentTask = undefined
  99. })
  100. })
  101. }
  102. // update the current scale value if the container size changes
  103. updateOnResize() {
  104. if (!this.isVisible()) {
  105. return
  106. }
  107. const currentScaleValue = this.viewer.currentScaleValue
  108. if (
  109. currentScaleValue === 'auto' ||
  110. currentScaleValue === 'page-fit' ||
  111. currentScaleValue === 'page-width'
  112. ) {
  113. this.viewer.currentScaleValue = currentScaleValue
  114. }
  115. this.viewer.update()
  116. }
  117. // get the page and offset of a click event
  118. clickPosition(event, pageElement, textLayer) {
  119. const { viewport } = this.viewer.getPageView(textLayer.pageNumber - 1)
  120. const pageRect = pageElement.querySelector('canvas').getBoundingClientRect()
  121. const dx = event.clientX - pageRect.left
  122. const dy = event.clientY - pageRect.top
  123. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  124. return {
  125. page: textLayer.pageNumber - 1,
  126. offset: {
  127. left,
  128. top: viewport.viewBox[3] - top,
  129. },
  130. }
  131. }
  132. // get the current page, offset and page size
  133. get currentPosition() {
  134. const pageIndex = this.viewer.currentPageNumber - 1
  135. const pageView = this.viewer.getPageView(pageIndex)
  136. const pageRect = pageView.div.getBoundingClientRect()
  137. const containerRect = this.container.getBoundingClientRect()
  138. const dy = containerRect.top - pageRect.top
  139. const dx = containerRect.left - pageRect.left
  140. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  141. const [, , width, height] = pageView.viewport.viewBox
  142. return {
  143. page: pageIndex,
  144. offset: { top, left },
  145. pageSize: { height, width },
  146. }
  147. }
  148. scrollToPosition(position, scale = null) {
  149. const destArray = [
  150. null,
  151. {
  152. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  153. },
  154. position.offset.left,
  155. position.offset.top,
  156. scale,
  157. ]
  158. this.viewer.scrollPageIntoView({
  159. pageNumber: position.page + 1,
  160. destArray,
  161. })
  162. // scroll the page down by an extra few pixels to account for the pdf.js viewer page border
  163. this.viewer.container.scrollBy({
  164. top: -9,
  165. })
  166. }
  167. isVisible() {
  168. return this.viewer.container.offsetParent !== null
  169. }
  170. abortDocumentLoading() {
  171. this.loadDocumentTask = undefined
  172. }
  173. destroy() {
  174. if (this.loadDocumentTask) {
  175. this.loadDocumentTask.destroy()
  176. this.loadDocumentTask = undefined
  177. }
  178. if (this.viewer) {
  179. this.viewer.destroy()
  180. }
  181. }
  182. }