pdf-js-wrapper.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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: any) => 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 (
  81. !error ||
  82. !(error instanceof PDFJS.ResponseException && error.missing === true)
  83. ) {
  84. captureException(error, {
  85. tags: { handler: 'pdf-preview' },
  86. })
  87. }
  88. throw error
  89. }
  90. }
  91. async fetchAllData() {
  92. await this.viewer.pdfDocument?.getData()
  93. }
  94. // update the current scale value if the container size changes
  95. updateOnResize() {
  96. if (!this.isVisible()) {
  97. return
  98. }
  99. // Use requestAnimationFrame to prevent errors like "ResizeObserver loop
  100. // completed with undelivered notifications" that can occur if updating the
  101. // viewer causes another repaint. The cost of this is that the viewer update
  102. // lags one frame behind, but it's unlikely to matter.
  103. // Further reading: https://github.com/WICG/resize-observer/issues/38
  104. window.requestAnimationFrame(() => {
  105. const currentScaleValue = this.viewer.currentScaleValue
  106. if (
  107. currentScaleValue === 'auto' ||
  108. currentScaleValue === 'page-fit' ||
  109. currentScaleValue === 'page-height' ||
  110. currentScaleValue === 'page-width'
  111. ) {
  112. this.viewer.currentScaleValue = currentScaleValue
  113. }
  114. this.viewer.update()
  115. })
  116. }
  117. // get the page and offset of a click event
  118. clickPosition(event: MouseEvent, canvas: HTMLCanvasElement, page: number) {
  119. if (!canvas) {
  120. return
  121. }
  122. const { viewport } = this.viewer.getPageView(page)
  123. const pageRect = canvas.getBoundingClientRect()
  124. const dx = event.clientX - pageRect.left
  125. const dy = event.clientY - pageRect.top
  126. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  127. return {
  128. page,
  129. offset: {
  130. left,
  131. top: viewport.viewBox[3] - top,
  132. },
  133. }
  134. }
  135. // get the current page, offset and page size
  136. get currentPosition() {
  137. const pageIndex = this.viewer.currentPageNumber - 1
  138. const pageView = this.viewer.getPageView(pageIndex)
  139. const pageRect = pageView.div.getBoundingClientRect()
  140. const containerRect = this.container.getBoundingClientRect()
  141. const dy = containerRect.top - pageRect.top
  142. const dx = containerRect.left - pageRect.left
  143. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  144. const [, , width, height] = pageView.viewport.viewBox
  145. return {
  146. page: pageIndex,
  147. offset: { top, left },
  148. pageSize: { height, width },
  149. }
  150. }
  151. scrollToPosition(position: Record<string, any>, scale = null) {
  152. const destArray = [
  153. null,
  154. {
  155. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  156. },
  157. position.offset.left,
  158. position.offset.top,
  159. scale,
  160. ]
  161. this.viewer.scrollPageIntoView({
  162. pageNumber: position.page + 1,
  163. destArray,
  164. })
  165. // scroll the page left and down by an extra few pixels to account for the pdf.js viewer page border
  166. const pageIndex = this.viewer.currentPageNumber - 1
  167. const pageView = this.viewer.getPageView(pageIndex)
  168. const offset = parseFloat(getComputedStyle(pageView.div).borderWidth)
  169. this.viewer.container.scrollBy({
  170. top: -offset,
  171. left: -offset,
  172. })
  173. }
  174. isVisible() {
  175. return this.viewer.container.offsetParent !== null
  176. }
  177. }