pdf-js-wrapper.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. import browser from '@/features/source-editor/extensions/browser'
  12. const DEFAULT_RANGE_CHUNK_SIZE = 128 * 1024 // 128K chunks
  13. export default class PDFJSWrapper {
  14. public readonly viewer: PDFViewer
  15. public readonly eventBus: EventBus
  16. private readonly linkService: PDFLinkService
  17. private readonly pdfCachingTransportFactory: any
  18. private url?: string
  19. // eslint-disable-next-line no-useless-constructor
  20. constructor(public container: HTMLDivElement) {
  21. // create the event bus
  22. this.eventBus = new EventBus()
  23. // create the link service
  24. this.linkService = new PDFLinkService({
  25. eventBus: this.eventBus,
  26. externalLinkTarget: LinkTarget.BLANK,
  27. externalLinkRel: 'noopener',
  28. })
  29. // create the viewer
  30. this.viewer = new PDFViewer({
  31. container: this.container,
  32. eventBus: this.eventBus,
  33. imageResourcesPath,
  34. linkService: this.linkService,
  35. maxCanvasPixels: browser.safari ? 4096 * 4096 : 8192 * 8192, // default is 4096 * 4096, increased for better resolution at high zoom levels (but not in Safari, which struggles with large canvases)
  36. annotationMode: PDFJS.AnnotationMode.ENABLE, // enable annotations but not forms
  37. annotationEditorMode: PDFJS.AnnotationEditorType.DISABLE, // disable annotation editing
  38. })
  39. this.linkService.setViewer(this.viewer)
  40. this.pdfCachingTransportFactory = generatePdfCachingTransportFactory()
  41. }
  42. // load a document from a URL
  43. async loadDocument({
  44. url,
  45. pdfFile,
  46. abortController,
  47. handleFetchError,
  48. }: {
  49. url: string
  50. pdfFile: Record<string, any>
  51. abortController: AbortController
  52. handleFetchError: (error: Error) => void
  53. }) {
  54. this.url = url
  55. const rangeTransport = this.pdfCachingTransportFactory({
  56. url,
  57. pdfFile,
  58. abortController,
  59. handleFetchError,
  60. })
  61. let rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE
  62. if (rangeTransport && pdfFile.size < 2 * DEFAULT_RANGE_CHUNK_SIZE) {
  63. // pdf.js disables the "bulk" download optimization when providing a
  64. // custom range transport. Restore it by bumping the chunk size.
  65. rangeChunkSize = pdfFile.size
  66. }
  67. try {
  68. const doc = await loadPdfDocumentFromUrl(url, {
  69. rangeChunkSize,
  70. range: rangeTransport,
  71. }).promise
  72. // check that this is still the current URL
  73. if (url !== this.url) {
  74. return
  75. }
  76. this.viewer.setDocument(doc)
  77. this.linkService.setDocument(doc)
  78. return doc
  79. } catch (error: any) {
  80. if (!error || error.name !== 'MissingPDFException') {
  81. captureException(error, {
  82. tags: { handler: 'pdf-preview' },
  83. })
  84. }
  85. throw error
  86. }
  87. }
  88. async fetchAllData() {
  89. await this.viewer.pdfDocument?.getData()
  90. }
  91. // update the current scale value if the container size changes
  92. updateOnResize() {
  93. if (!this.isVisible()) {
  94. return
  95. }
  96. // Use requestAnimationFrame to prevent errors like "ResizeObserver loop
  97. // completed with undelivered notifications" that can occur if updating the
  98. // viewer causes another repaint. The cost of this is that the viewer update
  99. // lags one frame behind, but it's unlikely to matter.
  100. // Further reading: https://github.com/WICG/resize-observer/issues/38
  101. window.requestAnimationFrame(() => {
  102. const currentScaleValue = this.viewer.currentScaleValue
  103. if (
  104. currentScaleValue === 'auto' ||
  105. currentScaleValue === 'page-fit' ||
  106. currentScaleValue === 'page-height' ||
  107. currentScaleValue === 'page-width'
  108. ) {
  109. this.viewer.currentScaleValue = currentScaleValue
  110. }
  111. this.viewer.update()
  112. })
  113. }
  114. // get the page and offset of a click event
  115. clickPosition(event: MouseEvent, canvas: HTMLCanvasElement, page: number) {
  116. if (!canvas) {
  117. return
  118. }
  119. const { viewport } = this.viewer.getPageView(page)
  120. const pageRect = 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,
  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: Record<string, any>, 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 left and down by an extra few pixels to account for the pdf.js viewer page border
  163. const pageIndex = this.viewer.currentPageNumber - 1
  164. const pageView = this.viewer.getPageView(pageIndex)
  165. const offset = parseFloat(getComputedStyle(pageView.div).borderWidth)
  166. this.viewer.container.scrollBy({
  167. top: -offset,
  168. left: -offset,
  169. })
  170. }
  171. isVisible() {
  172. return this.viewer.container.offsetParent !== null
  173. }
  174. }