pdf-js-wrapper.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. textLayerMode: 2, // PDFJSViewer.TextLayerMode.ENABLE,
  87. range: rangeTransport,
  88. })
  89. this.loadDocumentTask.promise
  90. .then(doc => {
  91. if (!this.loadDocumentTask) {
  92. return // ignoring the response since loading task has been aborted
  93. }
  94. const previousDoc = this.viewer.pdfDocument
  95. this.viewer.setDocument(doc)
  96. this.linkService.setDocument(doc)
  97. resolve(doc)
  98. if (previousDoc) {
  99. previousDoc.cleanup().catch(debugConsole.error)
  100. previousDoc.destroy()
  101. }
  102. })
  103. .catch(error => {
  104. if (this.loadDocumentTask) {
  105. if (!error || error.name !== 'MissingPDFException') {
  106. captureException(error, {
  107. tags: { handler: 'pdf-preview' },
  108. })
  109. }
  110. reject(error)
  111. }
  112. })
  113. .finally(() => {
  114. this.loadDocumentTask = undefined
  115. })
  116. })
  117. }
  118. // update the current scale value if the container size changes
  119. updateOnResize() {
  120. if (!this.isVisible()) {
  121. return
  122. }
  123. // Use requestAnimationFrame to prevent errors like "ResizeObserver loop
  124. // completed with undelivered notifications" that can occur if updating the
  125. // viewer causes another repaint. The cost of this is that the viewer update
  126. // lags one frame behind, but it's unlikely to matter.
  127. // Further reading: https://github.com/WICG/resize-observer/issues/38
  128. window.requestAnimationFrame(() => {
  129. const currentScaleValue = this.viewer.currentScaleValue
  130. if (
  131. currentScaleValue === 'auto' ||
  132. currentScaleValue === 'page-fit' ||
  133. currentScaleValue === 'page-width'
  134. ) {
  135. this.viewer.currentScaleValue = currentScaleValue
  136. }
  137. this.viewer.update()
  138. })
  139. }
  140. // get the page and offset of a click event
  141. clickPosition(event, pageElement, textLayer) {
  142. const { viewport } = this.viewer.getPageView(textLayer.pageNumber - 1)
  143. const pageCanvas = pageElement.querySelector('canvas')
  144. if (!pageCanvas) {
  145. return
  146. }
  147. const pageRect = pageCanvas.getBoundingClientRect()
  148. const dx = event.clientX - pageRect.left
  149. const dy = event.clientY - pageRect.top
  150. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  151. return {
  152. page: textLayer.pageNumber - 1,
  153. offset: {
  154. left,
  155. top: viewport.viewBox[3] - top,
  156. },
  157. }
  158. }
  159. // get the current page, offset and page size
  160. get currentPosition() {
  161. const pageIndex = this.viewer.currentPageNumber - 1
  162. const pageView = this.viewer.getPageView(pageIndex)
  163. const pageRect = pageView.div.getBoundingClientRect()
  164. const containerRect = this.container.getBoundingClientRect()
  165. const dy = containerRect.top - pageRect.top
  166. const dx = containerRect.left - pageRect.left
  167. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  168. const [, , width, height] = pageView.viewport.viewBox
  169. return {
  170. page: pageIndex,
  171. offset: { top, left },
  172. pageSize: { height, width },
  173. }
  174. }
  175. scrollToPosition(position, scale = null) {
  176. const destArray = [
  177. null,
  178. {
  179. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  180. },
  181. position.offset.left,
  182. position.offset.top,
  183. scale,
  184. ]
  185. this.viewer.scrollPageIntoView({
  186. pageNumber: position.page + 1,
  187. destArray,
  188. })
  189. // scroll the page left and down by an extra few pixels to account for the pdf.js viewer page border
  190. const pageIndex = this.viewer.currentPageNumber - 1
  191. const pageView = this.viewer.getPageView(pageIndex)
  192. const offset = parseFloat(getComputedStyle(pageView.div).borderWidth)
  193. this.viewer.container.scrollBy({
  194. top: -offset,
  195. left: -offset,
  196. })
  197. }
  198. isVisible() {
  199. return this.viewer.container.offsetParent !== null
  200. }
  201. abortDocumentLoading() {
  202. this.loadDocumentTask = undefined
  203. }
  204. destroy() {
  205. if (this.loadDocumentTask) {
  206. this.loadDocumentTask.destroy()
  207. this.loadDocumentTask = undefined
  208. }
  209. if (this.viewer) {
  210. this.viewer.destroy()
  211. }
  212. }
  213. }