pdf-js-wrapper.js 6.3 KB

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