pdf-js-wrapper.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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, 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. captureMessage(`pdf preview error ${error}`)
  104. }
  105. reject(error)
  106. }
  107. })
  108. .finally(() => {
  109. this.loadDocumentTask = undefined
  110. })
  111. })
  112. }
  113. // update the current scale value if the container size changes
  114. updateOnResize() {
  115. if (!this.isVisible()) {
  116. return
  117. }
  118. const currentScaleValue = this.viewer.currentScaleValue
  119. if (
  120. currentScaleValue === 'auto' ||
  121. currentScaleValue === 'page-fit' ||
  122. currentScaleValue === 'page-width'
  123. ) {
  124. this.viewer.currentScaleValue = currentScaleValue
  125. }
  126. this.viewer.update()
  127. }
  128. // get the page and offset of a click event
  129. clickPosition(event, pageElement, textLayer) {
  130. const { viewport } = this.viewer.getPageView(textLayer.pageNumber - 1)
  131. const pageCanvas = pageElement.querySelector('canvas')
  132. if (!pageCanvas) {
  133. return
  134. }
  135. const pageRect = pageCanvas.getBoundingClientRect()
  136. const dx = event.clientX - pageRect.left
  137. const dy = event.clientY - pageRect.top
  138. const [left, top] = viewport.convertToPdfPoint(dx, dy)
  139. return {
  140. page: textLayer.pageNumber - 1,
  141. offset: {
  142. left,
  143. top: viewport.viewBox[3] - top,
  144. },
  145. }
  146. }
  147. // get the current page, offset and page size
  148. get currentPosition() {
  149. const pageIndex = this.viewer.currentPageNumber - 1
  150. const pageView = this.viewer.getPageView(pageIndex)
  151. const pageRect = pageView.div.getBoundingClientRect()
  152. const containerRect = this.container.getBoundingClientRect()
  153. const dy = containerRect.top - pageRect.top
  154. const dx = containerRect.left - pageRect.left
  155. const [left, top] = pageView.viewport.convertToPdfPoint(dx, dy)
  156. const [, , width, height] = pageView.viewport.viewBox
  157. return {
  158. page: pageIndex,
  159. offset: { top, left },
  160. pageSize: { height, width },
  161. }
  162. }
  163. scrollToPosition(position, scale = null) {
  164. const destArray = [
  165. null,
  166. {
  167. name: 'XYZ', // 'XYZ' = scroll to the given coordinates
  168. },
  169. position.offset.left,
  170. position.offset.top,
  171. scale,
  172. ]
  173. this.viewer.scrollPageIntoView({
  174. pageNumber: position.page + 1,
  175. destArray,
  176. })
  177. // scroll the page down by an extra few pixels to account for the pdf.js viewer page border
  178. this.viewer.container.scrollBy({
  179. top: -9,
  180. })
  181. }
  182. isVisible() {
  183. return this.viewer.container.offsetParent !== null
  184. }
  185. abortDocumentLoading() {
  186. this.loadDocumentTask = undefined
  187. }
  188. destroy() {
  189. if (this.loadDocumentTask) {
  190. this.loadDocumentTask.destroy()
  191. this.loadDocumentTask = undefined
  192. }
  193. if (this.viewer) {
  194. this.viewer.destroy()
  195. }
  196. }
  197. }