pdf-js-wrapper.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { captureException } from '../../../infrastructure/error-reporter'
  2. import { generatePdfCachingTransportFactory } from './pdf-caching-transport'
  3. import { debugConsole } from '@/utils/debugging'
  4. const params = new URLSearchParams(window.location.search)
  5. const disableFontFace = params.get('disable-font-face') === 'true'
  6. const disableStream = process.env.NODE_ENV !== 'test'
  7. const DEFAULT_RANGE_CHUNK_SIZE = 128 * 1024 // 128K chunks
  8. export default class PDFJSWrapper {
  9. constructor(container) {
  10. this.container = container
  11. }
  12. async init() {
  13. const {
  14. PDFJS,
  15. PDFJSViewer,
  16. cMapUrl,
  17. imageResourcesPath,
  18. standardFontDataUrl,
  19. } = await import('./pdf-js-versions').then(m => {
  20. return m.default
  21. })
  22. this.PDFJS = PDFJS
  23. this.genPdfCachingTransport = generatePdfCachingTransportFactory(PDFJS)
  24. this.PDFJSViewer = PDFJSViewer
  25. this.cMapUrl = cMapUrl
  26. this.standardFontDataUrl = standardFontDataUrl
  27. this.imageResourcesPath = imageResourcesPath
  28. // create the event bus
  29. const eventBus = new PDFJSViewer.EventBus()
  30. // create the link service
  31. const linkService = new PDFJSViewer.PDFLinkService({
  32. eventBus,
  33. externalLinkTarget: 2,
  34. externalLinkRel: 'noopener',
  35. })
  36. // create the localization
  37. // const l10n = new PDFJSViewer.GenericL10n('en-GB') // TODO: locale mapping?
  38. // create the viewer
  39. const viewer = new PDFJSViewer.PDFViewer({
  40. container: this.container,
  41. eventBus,
  42. imageResourcesPath,
  43. linkService,
  44. // l10n, // commented out since it currently breaks `aria-label` rendering in pdf pages
  45. enableScripting: false, // default is false, but set explicitly to be sure
  46. enableXfa: false, // default is false (2021-10-12), but set explicitly to be sure
  47. renderInteractiveForms: false,
  48. maxCanvasPixels: 8192 * 8192, // default is 4096 * 4096, increased for better resolution at high zoom levels
  49. annotationMode: PDFJS.AnnotationMode?.ENABLE, // enable annotations but not forms
  50. annotationEditorMode: PDFJS.AnnotationEditorType?.DISABLE, // disable annotation editing
  51. })
  52. linkService.setViewer(viewer)
  53. this.eventBus = eventBus
  54. this.linkService = linkService
  55. this.viewer = viewer
  56. }
  57. // load a document from a URL
  58. loadDocument({ url, pdfFile, abortController, handleFetchError }) {
  59. // cancel any previous loading task
  60. if (this.loadDocumentTask) {
  61. this.loadDocumentTask.destroy()
  62. this.loadDocumentTask = undefined
  63. }
  64. return new Promise((resolve, reject) => {
  65. const rangeTransport = this.genPdfCachingTransport({
  66. url,
  67. pdfFile,
  68. abortController,
  69. handleFetchError,
  70. })
  71. let rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE
  72. if (rangeTransport && pdfFile.size < 2 * DEFAULT_RANGE_CHUNK_SIZE) {
  73. // pdf.js disables the "bulk" download optimization when providing a
  74. // custom range transport. Restore it by bumping the chunk size.
  75. rangeChunkSize = pdfFile.size
  76. }
  77. this.loadDocumentTask = this.PDFJS.getDocument({
  78. url,
  79. cMapUrl: this.cMapUrl,
  80. cMapPacked: true,
  81. standardFontDataUrl: this.standardFontDataUrl,
  82. disableFontFace,
  83. rangeChunkSize,
  84. disableAutoFetch: true,
  85. disableStream,
  86. isEvalSupported: false,
  87. textLayerMode: 2, // PDFJSViewer.TextLayerMode.ENABLE,
  88. range: rangeTransport,
  89. })
  90. this.loadDocumentTask.promise
  91. .then(doc => {
  92. if (!this.loadDocumentTask) {
  93. return // ignoring the response since loading task has been aborted
  94. }
  95. const previousDoc = this.viewer.pdfDocument
  96. this.viewer.setDocument(doc)
  97. this.linkService.setDocument(doc)
  98. resolve(doc)
  99. if (previousDoc) {
  100. previousDoc.cleanup().catch(debugConsole.error)
  101. previousDoc.destroy()
  102. }
  103. })
  104. .catch(error => {
  105. if (this.loadDocumentTask) {
  106. if (!error || error.name !== 'MissingPDFException') {
  107. captureException(error, {
  108. tags: { handler: 'pdf-preview' },
  109. })
  110. }
  111. reject(error)
  112. }
  113. })
  114. .finally(() => {
  115. this.loadDocumentTask = undefined
  116. })
  117. })
  118. }
  119. // update the current scale value if the container size changes
  120. updateOnResize() {
  121. if (!this.isVisible()) {
  122. return
  123. }
  124. // Use requestAnimationFrame to prevent errors like "ResizeObserver loop
  125. // completed with undelivered notifications" that can occur if updating the
  126. // viewer causes another repaint. The cost of this is that the viewer update
  127. // lags one frame behind, but it's unlikely to matter.
  128. // Further reading: https://github.com/WICG/resize-observer/issues/38
  129. window.requestAnimationFrame(() => {
  130. const currentScaleValue = this.viewer.currentScaleValue
  131. if (
  132. currentScaleValue === 'auto' ||
  133. currentScaleValue === 'page-fit' ||
  134. currentScaleValue === 'page-width'
  135. ) {
  136. this.viewer.currentScaleValue = currentScaleValue
  137. }
  138. this.viewer.update()
  139. })
  140. }
  141. // get the page and offset of a click event
  142. clickPosition(event, pageElement, textLayer) {
  143. const { viewport } = this.viewer.getPageView(textLayer.pageNumber - 1)
  144. const pageCanvas = pageElement.querySelector('canvas')
  145. if (!pageCanvas) {
  146. return
  147. }
  148. const pageRect = pageCanvas.getBoundingClientRect()
  149. const dx = event.clientX - pageRect.left
  150. const dy = event.clientY - pageRect.top
  151. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  152. return {
  153. page: textLayer.pageNumber - 1,
  154. offset: {
  155. left,
  156. top: viewport.viewBox[3] - top,
  157. },
  158. }
  159. }
  160. // get the current page, offset and page size
  161. get currentPosition() {
  162. const pageIndex = this.viewer.currentPageNumber - 1
  163. const pageView = this.viewer.getPageView(pageIndex)
  164. const pageRect = pageView.div.getBoundingClientRect()
  165. const containerRect = this.container.getBoundingClientRect()
  166. const dy = containerRect.top - pageRect.top
  167. const dx = containerRect.left - pageRect.left
  168. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  169. const [, , width, height] = pageView.viewport.viewBox
  170. return {
  171. page: pageIndex,
  172. offset: { top, left },
  173. pageSize: { height, width },
  174. }
  175. }
  176. scrollToPosition(position, scale = null) {
  177. const destArray = [
  178. null,
  179. {
  180. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  181. },
  182. position.offset.left,
  183. position.offset.top,
  184. scale,
  185. ]
  186. this.viewer.scrollPageIntoView({
  187. pageNumber: position.page + 1,
  188. destArray,
  189. })
  190. // scroll the page left and down by an extra few pixels to account for the pdf.js viewer page border
  191. const pageIndex = this.viewer.currentPageNumber - 1
  192. const pageView = this.viewer.getPageView(pageIndex)
  193. const offset = parseFloat(getComputedStyle(pageView.div).borderWidth)
  194. this.viewer.container.scrollBy({
  195. top: -offset,
  196. left: -offset,
  197. })
  198. }
  199. isVisible() {
  200. return this.viewer.container.offsetParent !== null
  201. }
  202. abortDocumentLoading() {
  203. this.loadDocumentTask = undefined
  204. }
  205. destroy() {
  206. if (this.loadDocumentTask) {
  207. this.loadDocumentTask.destroy()
  208. this.loadDocumentTask = undefined
  209. }
  210. if (this.viewer) {
  211. this.viewer.destroy()
  212. }
  213. }
  214. }