pdf-js-wrapper.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. })
  49. linkService.setViewer(viewer)
  50. this.eventBus = eventBus
  51. this.linkService = linkService
  52. this.viewer = viewer
  53. }
  54. // load a document from a URL
  55. loadDocument({ url, pdfFile, abortController, handleFetchError }) {
  56. // cancel any previous loading task
  57. if (this.loadDocumentTask) {
  58. this.loadDocumentTask.destroy()
  59. this.loadDocumentTask = undefined
  60. }
  61. return new Promise((resolve, reject) => {
  62. const rangeTransport = this.genPdfCachingTransport({
  63. url,
  64. pdfFile,
  65. abortController,
  66. handleFetchError,
  67. })
  68. let rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE
  69. if (rangeTransport && pdfFile.size < 2 * DEFAULT_RANGE_CHUNK_SIZE) {
  70. // pdf.js disables the "bulk" download optimization when providing a
  71. // custom range transport. Restore it by bumping the chunk size.
  72. rangeChunkSize = pdfFile.size
  73. }
  74. this.loadDocumentTask = this.PDFJS.getDocument({
  75. url,
  76. cMapUrl: this.cMapUrl,
  77. cMapPacked: true,
  78. standardFontDataUrl: this.standardFontDataUrl,
  79. disableFontFace,
  80. rangeChunkSize,
  81. disableAutoFetch: true,
  82. disableStream,
  83. textLayerMode: 2, // PDFJSViewer.TextLayerMode.ENABLE,
  84. range: rangeTransport,
  85. })
  86. this.loadDocumentTask.promise
  87. .then(doc => {
  88. if (!this.loadDocumentTask) {
  89. return // ignoring the response since loading task has been aborted
  90. }
  91. const previousDoc = this.viewer.pdfDocument
  92. this.viewer.setDocument(doc)
  93. this.linkService.setDocument(doc)
  94. resolve(doc)
  95. if (previousDoc) {
  96. previousDoc.cleanup().catch(console.error)
  97. previousDoc.destroy()
  98. }
  99. })
  100. .catch(error => {
  101. if (this.loadDocumentTask) {
  102. if (!error || error.name !== 'MissingPDFException') {
  103. captureException(error, {
  104. tags: { handler: 'pdf-preview' },
  105. })
  106. }
  107. reject(error)
  108. }
  109. })
  110. .finally(() => {
  111. this.loadDocumentTask = undefined
  112. })
  113. })
  114. }
  115. // update the current scale value if the container size changes
  116. updateOnResize() {
  117. if (!this.isVisible()) {
  118. return
  119. }
  120. const currentScaleValue = this.viewer.currentScaleValue
  121. if (
  122. currentScaleValue === 'auto' ||
  123. currentScaleValue === 'page-fit' ||
  124. currentScaleValue === 'page-width'
  125. ) {
  126. this.viewer.currentScaleValue = currentScaleValue
  127. }
  128. this.viewer.update()
  129. }
  130. // get the page and offset of a click event
  131. clickPosition(event, pageElement, textLayer) {
  132. const { viewport } = this.viewer.getPageView(textLayer.pageNumber - 1)
  133. const pageCanvas = pageElement.querySelector('canvas')
  134. if (!pageCanvas) {
  135. return
  136. }
  137. const pageRect = pageCanvas.getBoundingClientRect()
  138. const dx = event.clientX - pageRect.left
  139. const dy = event.clientY - pageRect.top
  140. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  141. return {
  142. page: textLayer.pageNumber - 1,
  143. offset: {
  144. left,
  145. top: viewport.viewBox[3] - top,
  146. },
  147. }
  148. }
  149. // get the current page, offset and page size
  150. get currentPosition() {
  151. const pageIndex = this.viewer.currentPageNumber - 1
  152. const pageView = this.viewer.getPageView(pageIndex)
  153. const pageRect = pageView.div.getBoundingClientRect()
  154. const containerRect = this.container.getBoundingClientRect()
  155. const dy = containerRect.top - pageRect.top
  156. const dx = containerRect.left - pageRect.left
  157. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  158. const [, , width, height] = pageView.viewport.viewBox
  159. return {
  160. page: pageIndex,
  161. offset: { top, left },
  162. pageSize: { height, width },
  163. }
  164. }
  165. scrollToPosition(position, scale = null) {
  166. const destArray = [
  167. null,
  168. {
  169. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  170. },
  171. position.offset.left,
  172. position.offset.top,
  173. scale,
  174. ]
  175. this.viewer.scrollPageIntoView({
  176. pageNumber: position.page + 1,
  177. destArray,
  178. })
  179. // scroll the page down by an extra few pixels to account for the pdf.js viewer page border
  180. this.viewer.container.scrollBy({
  181. top: -9,
  182. })
  183. }
  184. isVisible() {
  185. return this.viewer.container.offsetParent !== null
  186. }
  187. abortDocumentLoading() {
  188. this.loadDocumentTask = undefined
  189. }
  190. destroy() {
  191. if (this.loadDocumentTask) {
  192. this.loadDocumentTask.destroy()
  193. this.loadDocumentTask = undefined
  194. }
  195. if (this.viewer) {
  196. this.viewer.destroy()
  197. }
  198. }
  199. }