pdf-js-wrapper.ts 6.0 KB

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