index.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const ComPDFKitViewer = {
  2. init (options, element) {
  3. return new Promise((resolve) => {
  4. element.addEventListener("ready", function ready () {
  5. element.removeEventListener('ready', ready)
  6. const iframeWindow = element.querySelector('iframe').contentWindow
  7. Promise.resolve().then(function() {
  8. resolve({
  9. docViewer: iframeWindow.instance
  10. })
  11. })
  12. })
  13. const viewer = new Viewer(options, element)
  14. })
  15. }
  16. }
  17. class Viewer {
  18. constructor (options, element) {
  19. this.instance = null
  20. this.options = options
  21. this.initialDoc = options.pdfUrl || null
  22. this.element = element
  23. element.addEventListener("ready", (function ready() {
  24. element.removeEventListener("ready", ready)
  25. }))
  26. this.create()
  27. }
  28. _createEvent (e, t) {
  29. let n;
  30. try {
  31. n = new CustomEvent(e, {
  32. detail: t,
  33. bubbles: true,
  34. cancelable: true
  35. })
  36. } catch (o) {
  37. (n = document.createEvent("Event")).initEvent(e, true, true),
  38. n.detail = t
  39. }
  40. return n
  41. }
  42. create() {
  43. if (this.initialDoc) {
  44. this.initialDoc = encodeURIComponent(this.initialDoc)
  45. this._create()
  46. } else {
  47. this._create()
  48. }
  49. }
  50. _create () {
  51. if (!this._trigger) {
  52. this._trigger = function(e, t) {
  53. var n = this._createEvent(e, t);
  54. this.element.dispatchEvent(n)
  55. }
  56. }
  57. this.createViewer()
  58. }
  59. createViewer () {
  60. const self = this
  61. let webviewerUrl = './webviewer/index.html'
  62. if (this.initialDoc) {
  63. webviewerUrl += "#d=\"".concat(decodeURIComponent(this.initialDoc)).concat("\"")
  64. }
  65. const iframe = document.createElement("iframe")
  66. iframe.id = "webviewer-".concat(this.id)
  67. iframe.src = webviewerUrl
  68. iframe.title = "webviewer"
  69. iframe.frameBorder = 0
  70. iframe.width = "100%"
  71. iframe.height = "100%"
  72. iframe.setAttribute("allowfullscreen", true)
  73. iframe.setAttribute("webkitallowfullscreen", true)
  74. iframe.setAttribute("mozallowfullscreen", true)
  75. this.iframe = iframe
  76. this.options?.backgroundColor && iframe.setAttribute("data-bgcolor", this.options.backgroundColor),
  77. this.options?.assetPath && iframe.setAttribute("data-assetpath", encodeURIComponent(this.options.assetPath)),
  78. this.loadListener = function() {
  79. var $iframe = self.iframe;
  80. self.instance = $iframe.contentWindow.instance;
  81. $iframe.contentWindow.instance.initApiUrl(self.options)
  82. self._trigger("ready");
  83. },
  84. iframe.addEventListener("load", this.loadListener),
  85. this.element.appendChild(iframe)
  86. }
  87. }
  88. export default ComPDFKitViewer