pdf-js-wrapper.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. // Hold the .pdfViewer element's height steady across the synchronous page-clear
  78. // that setDocument() triggers, so the viewer doesn't visually collapse while the
  79. // new pages are being initialised. The min-height is released on pagesinit.
  80. const viewerEl = this.container.querySelector('.pdfViewer') as HTMLElement
  81. const currentHeight = viewerEl.getBoundingClientRect().height
  82. if (currentHeight > 0) {
  83. viewerEl.style.minHeight = `${currentHeight}px`
  84. const clearMinHeight = () => {
  85. viewerEl.style.minHeight = ''
  86. this.eventBus.off('pagesinit', clearMinHeight)
  87. }
  88. this.eventBus.on('pagesinit', clearMinHeight)
  89. }
  90. const setDocument = () => {
  91. this.viewer.setDocument(doc)
  92. this.linkService.setDocument(doc)
  93. }
  94. const container = this.container as typeof this.container & {
  95. // supported since Chrome 147
  96. startViewTransition?: (cb: () => void | Promise<void>) => {
  97. ready: Promise<void>
  98. }
  99. }
  100. if (
  101. typeof container.startViewTransition === 'function' &&
  102. document.visibilityState !== 'hidden'
  103. ) {
  104. const transition = container.startViewTransition(setDocument)
  105. transition.ready.catch(err => {
  106. // ignore InvalidStateError, it just means the document was hidden
  107. if (err?.name !== 'InvalidStateError') {
  108. captureException(err, {
  109. tags: { handler: 'pdf-preview' },
  110. })
  111. }
  112. })
  113. } else {
  114. setDocument()
  115. }
  116. return doc
  117. } catch (error: any) {
  118. if (
  119. !error ||
  120. !(error instanceof PDFJS.ResponseException && error.missing === true)
  121. ) {
  122. captureException(error, {
  123. tags: { handler: 'pdf-preview' },
  124. })
  125. }
  126. throw error
  127. }
  128. }
  129. async fetchAllData() {
  130. await this.viewer.pdfDocument?.getData()
  131. }
  132. // update the current scale value if the container size changes
  133. updateOnResize() {
  134. if (!this.isVisible()) {
  135. return
  136. }
  137. // Use requestAnimationFrame to prevent errors like "ResizeObserver loop
  138. // completed with undelivered notifications" that can occur if updating the
  139. // viewer causes another repaint. The cost of this is that the viewer update
  140. // lags one frame behind, but it's unlikely to matter.
  141. // Further reading: https://github.com/WICG/resize-observer/issues/38
  142. window.requestAnimationFrame(() => {
  143. const currentScaleValue = this.viewer.currentScaleValue
  144. if (
  145. currentScaleValue === 'auto' ||
  146. currentScaleValue === 'page-fit' ||
  147. currentScaleValue === 'page-height' ||
  148. currentScaleValue === 'page-width'
  149. ) {
  150. this.viewer.currentScaleValue = currentScaleValue
  151. }
  152. this.viewer.update()
  153. })
  154. }
  155. // get the page and offset of a click event
  156. clickPosition(event: MouseEvent, canvas: HTMLCanvasElement, page: number) {
  157. if (!canvas) {
  158. return
  159. }
  160. const { viewport } = this.viewer.getPageView(page)
  161. const pageRect = canvas.getBoundingClientRect()
  162. const dx = event.clientX - pageRect.left
  163. const dy = event.clientY - pageRect.top
  164. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  165. return {
  166. page,
  167. offset: {
  168. left,
  169. top: viewport.viewBox[3] - top,
  170. },
  171. }
  172. }
  173. // get the current page, offset and page size
  174. get currentPosition() {
  175. const containerRect = this.container.getBoundingClientRect()
  176. let pageIndex = this.viewer.currentPageNumber - 1
  177. for (let i = pageIndex; i >= 0; i--) {
  178. const pageView = this.viewer.getPageView(i)
  179. if (!pageView?.div) continue
  180. const pageRect = pageView.div.getBoundingClientRect()
  181. if (pageRect.bottom < containerRect.top) {
  182. pageIndex = i + 1
  183. break
  184. }
  185. pageIndex = i
  186. }
  187. const pageView = this.viewer.getPageView(pageIndex)
  188. const pageRect = pageView.div.getBoundingClientRect()
  189. const dy = containerRect.top - pageRect.top
  190. const dx = containerRect.left - pageRect.left
  191. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  192. const [, , width, height] = pageView.viewport.viewBox
  193. return {
  194. page: pageIndex,
  195. offset: { top, left },
  196. pageSize: { height, width },
  197. }
  198. }
  199. scrollToPosition(position: Record<string, any>, scale = null) {
  200. const destArray = [
  201. null,
  202. {
  203. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  204. },
  205. position.offset.left,
  206. position.offset.top,
  207. scale,
  208. ]
  209. this.viewer.scrollPageIntoView({
  210. pageNumber: position.page + 1,
  211. destArray,
  212. })
  213. // scrollPageIntoView aligns PDF content to the container top, ignoring the page margin.
  214. // For a top-of-document position this leaves scrollTop = marginTop (margin hidden).
  215. // Snap back to 0 so the margin is visible, but only when we are in that margin band —
  216. // for any real mid-document scrollTop this condition is false and we leave it untouched.
  217. const pageIndex = this.viewer.currentPageNumber - 1
  218. const pageView = this.viewer.getPageView(pageIndex)
  219. if (pageView) {
  220. const marginTop = parseFloat(getComputedStyle(pageView.div).marginTop)
  221. if (this.viewer.container.scrollTop <= marginTop) {
  222. this.viewer.container.scrollTop = 0
  223. }
  224. }
  225. }
  226. isVisible() {
  227. return this.viewer.container.offsetParent !== null
  228. }
  229. }