pdf-js-wrapper.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { captureException } from '@/infrastructure/error-reporter'
  2. import { generatePdfCachingTransportFactory } from './pdf-caching-transport'
  3. import { PDFJS, loadPdfDocumentFromUrl, imageResourcesPath } from './pdf-js'
  4. import {
  5. PDFViewer,
  6. EventBus,
  7. PDFLinkService,
  8. LinkTarget,
  9. } from 'pdfjs-dist/web/pdf_viewer.mjs'
  10. import 'pdfjs-dist/web/pdf_viewer.css'
  11. const DEFAULT_RANGE_CHUNK_SIZE = 128 * 1024 // 128K chunks
  12. export default class PDFJSWrapper {
  13. public readonly viewer: PDFViewer
  14. public readonly eventBus: EventBus
  15. private readonly linkService: PDFLinkService
  16. private readonly pdfCachingTransportFactory: any
  17. private url?: string
  18. // eslint-disable-next-line no-useless-constructor
  19. constructor(public container: HTMLDivElement) {
  20. // create the event bus
  21. this.eventBus = new EventBus()
  22. // create the link service
  23. this.linkService = new PDFLinkService({
  24. eventBus: this.eventBus,
  25. externalLinkTarget: LinkTarget.BLANK,
  26. externalLinkRel: 'noopener',
  27. })
  28. // create the viewer
  29. this.viewer = new PDFViewer({
  30. container: this.container,
  31. eventBus: this.eventBus,
  32. imageResourcesPath,
  33. linkService: this.linkService,
  34. maxCanvasPixels: 8192 * 8192, // default is 4096 * 4096, increased for better resolution at high zoom levels
  35. annotationMode: PDFJS.AnnotationMode.ENABLE, // enable annotations but not forms
  36. annotationEditorMode: PDFJS.AnnotationEditorType.DISABLE, // disable annotation editing
  37. })
  38. this.linkService.setViewer(this.viewer)
  39. this.pdfCachingTransportFactory = generatePdfCachingTransportFactory()
  40. }
  41. // load a document from a URL
  42. async loadDocument({
  43. url,
  44. pdfFile,
  45. abortController,
  46. handleFetchError,
  47. }: {
  48. url: string
  49. pdfFile: Record<string, any>
  50. abortController: AbortController
  51. handleFetchError: (error: Error) => void
  52. }) {
  53. this.url = url
  54. const rangeTransport = this.pdfCachingTransportFactory({
  55. url,
  56. pdfFile,
  57. abortController,
  58. handleFetchError,
  59. })
  60. let rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE
  61. if (rangeTransport && pdfFile.size < 2 * DEFAULT_RANGE_CHUNK_SIZE) {
  62. // pdf.js disables the "bulk" download optimization when providing a
  63. // custom range transport. Restore it by bumping the chunk size.
  64. rangeChunkSize = pdfFile.size
  65. }
  66. try {
  67. const doc = await loadPdfDocumentFromUrl(url, {
  68. rangeChunkSize,
  69. range: rangeTransport,
  70. }).promise
  71. // check that this is still the current URL
  72. if (url !== this.url) {
  73. return
  74. }
  75. this.viewer.setDocument(doc)
  76. this.linkService.setDocument(doc)
  77. return doc
  78. } catch (error: any) {
  79. if (!error || error.name !== 'MissingPDFException') {
  80. captureException(error, {
  81. tags: { handler: 'pdf-preview' },
  82. })
  83. }
  84. throw error
  85. }
  86. }
  87. async fetchAllData() {
  88. await this.viewer.pdfDocument?.getData()
  89. }
  90. // update the current scale value if the container size changes
  91. updateOnResize() {
  92. if (!this.isVisible()) {
  93. return
  94. }
  95. // Use requestAnimationFrame to prevent errors like "ResizeObserver loop
  96. // completed with undelivered notifications" that can occur if updating the
  97. // viewer causes another repaint. The cost of this is that the viewer update
  98. // lags one frame behind, but it's unlikely to matter.
  99. // Further reading: https://github.com/WICG/resize-observer/issues/38
  100. window.requestAnimationFrame(() => {
  101. const currentScaleValue = this.viewer.currentScaleValue
  102. if (
  103. currentScaleValue === 'auto' ||
  104. currentScaleValue === 'page-fit' ||
  105. currentScaleValue === 'page-height' ||
  106. currentScaleValue === 'page-width'
  107. ) {
  108. this.viewer.currentScaleValue = currentScaleValue
  109. }
  110. this.viewer.update()
  111. })
  112. }
  113. // get the page and offset of a click event
  114. clickPosition(event: MouseEvent, canvas: HTMLCanvasElement, page: number) {
  115. if (!canvas) {
  116. return
  117. }
  118. const { viewport } = this.viewer.getPageView(page)
  119. const pageRect = canvas.getBoundingClientRect()
  120. const dx = event.clientX - pageRect.left
  121. const dy = event.clientY - pageRect.top
  122. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  123. return {
  124. page,
  125. offset: {
  126. left,
  127. top: viewport.viewBox[3] - top,
  128. },
  129. }
  130. }
  131. // get the current page, offset and page size
  132. get currentPosition() {
  133. const pageIndex = this.viewer.currentPageNumber - 1
  134. const pageView = this.viewer.getPageView(pageIndex)
  135. const pageRect = pageView.div.getBoundingClientRect()
  136. const containerRect = this.container.getBoundingClientRect()
  137. const dy = containerRect.top - pageRect.top
  138. const dx = containerRect.left - pageRect.left
  139. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  140. const [, , width, height] = pageView.viewport.viewBox
  141. return {
  142. page: pageIndex,
  143. offset: { top, left },
  144. pageSize: { height, width },
  145. }
  146. }
  147. scrollToPosition(position: Record<string, any>, scale = null) {
  148. const destArray = [
  149. null,
  150. {
  151. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  152. },
  153. position.offset.left,
  154. position.offset.top,
  155. scale,
  156. ]
  157. this.viewer.scrollPageIntoView({
  158. pageNumber: position.page + 1,
  159. destArray,
  160. })
  161. // scroll the page left and down by an extra few pixels to account for the pdf.js viewer page border
  162. const pageIndex = this.viewer.currentPageNumber - 1
  163. const pageView = this.viewer.getPageView(pageIndex)
  164. const offset = parseFloat(getComputedStyle(pageView.div).borderWidth)
  165. this.viewer.container.scrollBy({
  166. top: -offset,
  167. left: -offset,
  168. })
  169. }
  170. isVisible() {
  171. return this.viewer.container.offsetParent !== null
  172. }
  173. }