pdf-js-wrapper.js 6.7 KB

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