pdfjs-viewer-element 4.0.1 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -2
- package/dist/pdfjs-viewer-element.js +1 -1
- package/dist/viewer.css +1 -1
- package/package.json +15 -12
- package/types/pdfjs-viewer-element.d.ts +24 -21
package/README.md
CHANGED
|
@@ -16,6 +16,7 @@ Standalone, isolated, drop-in PDF viewer web component, based on [PDF.js default
|
|
|
16
16
|
- Configure via attributes (page, zoom, search, pagemode, locale)
|
|
17
17
|
- Resource path attributes for PDF.js internals (`worker-src`, `c-map-url`, `icc-url`, `standard-font-data-url`, `wasm-url`, and more)
|
|
18
18
|
- Built-in worker is enabled by default for stricter CSP compatibility
|
|
19
|
+
- Bundler friendly: Vite, Rollup and webpack pick up the viewer runtime files automatically, `assets-base` covers everything else
|
|
19
20
|
- Configure `PDFViewerApplicationOptions` via the `setViewerOptions` method
|
|
20
21
|
- Access to `PDFViewerApplication` via the `initPromise` property
|
|
21
22
|
- Built-in Paper & Ink default theme, with theme control (automatic/light/dark) and custom CSS injection
|
|
@@ -83,7 +84,8 @@ The element is block-level and needs an explicit height.
|
|
|
83
84
|
| `locale` | Viewer UI locale (for example `en-US`, `de`, `uk`). [Available locales](https://github.com/mozilla/pdf.js/tree/master/l10n) | `''` |
|
|
84
85
|
| `locale-src-template` | Locale file URL template. Must contain `{locale}` placeholder. Used together with `locale`. | `https://cdn.jsdelivr.net/gh/mozilla-l10n/firefox-l10n@main/{locale}/toolkit/toolkit/pdfviewer/viewer.ftl` |
|
|
85
86
|
| `viewer-css-theme` | Viewer theme: `AUTOMATIC`, `LIGHT`, `DARK`. | `AUTOMATIC` |
|
|
86
|
-
| `
|
|
87
|
+
| `assets-base` | Directory URL of the viewer runtime files (`viewer.mjs`, `pdf.mjs`, `pdf.worker.min.mjs`, `viewer.css`, `paper-and-ink.css`). Only needed when your bundler does not handle `new URL('./file', import.meta.url)`, see [Bundlers](#bundlers-and-assets-base). | folder of `pdfjs-viewer-element.js` |
|
|
88
|
+
| `worker-src` | PDF.js worker URL override. | bundled worker (`./build/pdf.worker.mjs` in dev, `pdf.worker.min.mjs` next to the element or in `assets-base`) |
|
|
87
89
|
| `debugger-src` | PDF.js debugger script URL (`debuggerSrc` option). | `./debugger.mjs` |
|
|
88
90
|
| `c-map-url` | CMap directory URL (`cMapUrl` option). | `../web/cmaps/` |
|
|
89
91
|
| `icc-url` | ICC profile directory URL (`iccUrl` option). | `../web/iccs/` |
|
|
@@ -103,13 +105,34 @@ Most attributes can be updated dynamically:
|
|
|
103
105
|
- `viewer-css-theme` updates the viewer theme at runtime.
|
|
104
106
|
- `worker-src`, `debugger-src`, `c-map-url`, `icc-url`, `image-resources-path`, `sandbox-bundle-src`, `standard-font-data-url`, `wasm-url` update viewer options for subsequent document loads.
|
|
105
107
|
- `locale` rebuilds the viewer so localization resources can be applied.
|
|
108
|
+
- `assets-base` and `locale-src-template` are read when the viewer is (re)initialized, so set them before the element is attached.
|
|
109
|
+
|
|
110
|
+
## Bundlers and assets base
|
|
111
|
+
|
|
112
|
+
The component loads the PDF.js viewer at runtime from five files shipped in the package `dist` folder: `viewer.mjs`, `pdf.mjs`, `pdf.worker.min.mjs`, `viewer.css` and `paper-and-ink.css`. They are referenced as `new URL('./file', import.meta.url)`, and each one is self-contained, so bundlers that understand this pattern emit them as hashed assets and rewrite the URLs on their own. Nothing to configure for Vite (build and dev), Rollup or webpack 5.
|
|
113
|
+
|
|
114
|
+
Bundlers that do not analyse `new URL(..., import.meta.url)`, esbuild among them, move the element into an app chunk without the files, and the viewer fails with 404s. Serve the package `dist` folder from a static path and point `assets-base` at it. The same attribute lets you load the files from a CDN:
|
|
115
|
+
|
|
116
|
+
```html
|
|
117
|
+
<pdfjs-viewer-element
|
|
118
|
+
src="/file.pdf"
|
|
119
|
+
assets-base="https://cdn.jsdelivr.net/npm/pdfjs-viewer-element@4/dist/">
|
|
120
|
+
</pdfjs-viewer-element>
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- The value is a directory URL, relative to the page or absolute. A trailing slash is added when missing.
|
|
124
|
+
- `worker-src` still takes precedence for the worker file.
|
|
125
|
+
- The attribute is read when the viewer is (re)initialized, so set it before the element is attached to the document.
|
|
126
|
+
|
|
127
|
+
PDF.js annotation icons are a separate case: the viewer loads them at runtime as `imageResourcesPath + 'annotation-' + name + '.svg'`, a dynamic name no bundler can emit. If you need them, serve the package `dist/images` folder and set `image-resources-path`.
|
|
106
128
|
|
|
107
129
|
## Worker source
|
|
108
130
|
|
|
109
131
|
By default, the component uses the bundled worker (same-origin), which is CSP-friendly in strict `script-src 'self'` environments.
|
|
110
132
|
|
|
111
133
|
- Dev mode default: `./build/pdf.worker.mjs`
|
|
112
|
-
- Dist/default package default:
|
|
134
|
+
- Dist/default package default: `pdf.worker.min.mjs` next to `pdfjs-viewer-element.js`, or the hashed copy your bundler emitted
|
|
135
|
+
- With `assets-base`: `pdf.worker.min.mjs` inside that folder
|
|
113
136
|
|
|
114
137
|
Set `worker-src` only if you want to serve the worker from a custom location (for example your own CDN or static assets path).
|
|
115
138
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=new URL("./pdf.worker.min.mjs",""+import.meta.url).href,t=new URL("./pdf.mjs",""+import.meta.url).href,i=new URL("./viewer.mjs",""+import.meta.url).href,r=new URL("./viewer.css",""+import.meta.url).href,s=new URL("./paper-and-ink.css",""+import.meta.url).href,a={src:"",iframeTitle:"PDF viewer window",page:"",search:"",phrase:"",zoom:"",pagemode:"none",locale:"",viewerCssTheme:"AUTOMATIC",workerSrc:e,debuggerSrc:"./debugger.mjs",cMapUrl:"../web/cmaps/",iccUrl:"../web/iccs/",imageResourcesPath:"./images/",sandboxBundleSrc:"../build/pdf.sandbox.mjs",standardFontDataUrl:"../web/standard_fonts/",wasmUrl:"../web/wasm/",localeSrcTemplate:"https://cdn.jsdelivr.net/gh/mozilla-l10n/firefox-l10n@main/{locale}/toolkit/toolkit/pdfviewer/viewer.ftl"},n={AUTOMATIC:0,LIGHT:1,DARK:2},o=class extends HTMLElement{constructor(){super(),this.initPromise=Promise.resolve({}),this.viewerStyles=new Set,this.optionsToSet={},this.applyIframeHash=async()=>{const e=this.iframe?.contentWindow;if(!e)return;const t=this.getIframeLocationHash();e.location.hash!==t&&await new Promise(i=>{let r=!1;const s=()=>{r||(r=!0,e.removeEventListener("hashchange",s),i())};e.addEventListener("hashchange",s),e.location.hash=t,queueMicrotask(()=>{e.location.hash===t&&s()})})},this.applyLocaleAtRuntime=async()=>{const e=this.iframe.contentWindow?.PDFViewerApplication,t=this.iframe.contentDocument;if(!e||!t)return!1;await e.initializedPromise;const i=e.externalServices?.createL10n;if("function"!=typeof i)return!1;const r=await i();if(!r)return!1;await(e.l10n?.destroy?.()),e.l10n=r;const s=e.appConfig?.appContainer||t.documentElement;return!!s&&("function"==typeof r.getDirection&&t.documentElement?.setAttribute("dir",r.getDirection()),"function"==typeof r.translate&&await r.translate(s),!0)},this.injectLocaleData=async()=>{const e=this.iframe.contentDocument,t=this.getAttribute("locale");if(!t)return void this.cleanupLocaleResource();const i=await(import("./locale-kKW4I85A.js"));if(!Object.keys(JSON.parse(i.default)).includes(t))return void this.cleanupLocaleResource();const r=this.formatTemplate(this.getAttribute("locale-src-template")||a.localeSrcTemplate,{locale:t}),s={[String(t)]:r},n=e.createElement("link");n.rel="resource",n.type="application/l10n",this.cleanupLocaleResource(),this.localeResourceUrl=URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),n.href=this.localeResourceUrl,this.iframe.contentDocument?.head.appendChild(n),this.localeResourceLink=n},this.onViewerAppCreated=()=>new Promise(e=>{const t=this.iframe.contentWindow;if(t.PDFViewerApplication)return e(t.PDFViewerApplication);let i;Object.defineProperty(t,"PDFViewerApplication",{get:()=>i,set(r){i=r,e(r),delete t.PDFViewerApplication,t.PDFViewerApplication=r},configurable:!0})}),this.applyViewerOptions=()=>{const e=this.iframe.contentWindow?.PDFViewerApplicationOptions;e?.set("workerSrc",this.getAttribute("worker-src")||a.workerSrc),e?.set("debuggerSrc",this.getAttribute("debugger-src")||a.debuggerSrc),e?.set("cMapUrl",this.getAttribute("c-map-url")||a.cMapUrl),e?.set("iccUrl",this.getAttribute("icc-url")||a.iccUrl),e?.set("imageResourcesPath",this.getAttribute("image-resources-path")||a.imageResourcesPath),e?.set("sandboxBundleSrc",this.getAttribute("sandbox-bundle-src")||a.sandboxBundleSrc),e?.set("standardFontDataUrl",this.getAttribute("standard-font-data-url")||a.standardFontDataUrl),e?.set("wasmUrl",this.getAttribute("wasm-url")||a.wasmUrl),e?.set("defaultUrl",this.getFullPath(this.getAttribute("src")||a.src)),e?.set("disablePreferences",!0),e?.set("eventBusDispatchToDOM",!0),e?.set("localeProperties",{lang:this.getAttribute("locale")||a.locale}),e?.set("viewerCssTheme",this.getCssThemeOption());for(const[t,i]of Object.entries(this.optionsToSet))e?.set(t,i);this.optionsToSet={}},this.getIframeLocationHash=()=>{const e={page:this.getAttribute("page")||a.page,zoom:this.getAttribute("zoom")||a.zoom,pagemode:this.getAttribute("pagemode")||a.pagemode,search:this.getAttribute("search")||a.search,phrase:this.getAttribute("phrase")||a.phrase,locale:this.getAttribute("locale")||a.locale};return"#"+Object.entries(e).map(([e,t])=>`${e}=${t}`).join("&")},this.buildViewerEntry=async()=>new Promise(async e=>{const n=await(import("./_virtual_pdfjs-viewer-html-Db40JDMA.js")),o=e=>{try{const t=new URL(e,window.location.href);if("http:"===t.protocol||"https:"===t.protocol)return t.origin}catch{}return""},c=e=>Array.from(new Set(e.filter(Boolean))).join(" "),l=c(["'self'",window.location.origin,o(t),o(i)]),h=c(["'self'",window.location.origin,o(r),o(s)]),p=["default-src 'none'",`script-src ${l} 'wasm-unsafe-eval'`,`script-src-elem ${l}`,`worker-src ${c(["'self'","blob:",window.location.origin,o(this.getAttribute("worker-src")||a.workerSrc)])}`,`style-src ${h} 'unsafe-inline'`,`img-src ${h} blob: data:`,"media-src blob:",`font-src ${h} data:`,"connect-src * blob: data:","base-uri 'none'","form-action 'none'"].join("; "),u=n.default.replace(/<meta\s+http-equiv="Content-Security-Policy"[^>]*>/i,`<meta http-equiv="Content-Security-Policy" content="${p};" />`).replace("</head>",`\n <link rel="stylesheet" href="${r}">\n <link rel="stylesheet" href="${s}">\n ${Array.from(this.viewerStyles).map(e=>`<style>${e}</style>`).join("\n")}\n </head>`);this.iframe.addEventListener("load",()=>e(),{once:!0}),this.iframe.srcdoc=u}),this.setupViewerApp=async()=>{const e=await this.onViewerAppCreated();return this.applyViewerOptions(),await(e?.initializedPromise),this.applyViewerTheme(),this.applyQueuedRuntimeStyles(),{viewerApp:e}},this.buildViewerApp=async()=>{await this.applyIframeHash();const e=this.setupViewerApp();return await this.injectLocaleData(),await this.injectScript(t),await this.injectScript(i),await e},this.attachShadow({mode:"open"}).innerHTML='\n <style>:host{width:100%;display:block;overflow:hidden}:host iframe{height:100%}</style>\n <iframe frameborder="0" width="100%" loading="lazy"></iframe>\n '}static get observedAttributes(){return["src","locale","viewer-css-theme","worker-src","debugger-src","c-map-url","icc-url","image-resources-path","sandbox-bundle-src","standard-font-data-url","wasm-url","page","search","phrase","zoom","pagemode","iframe-title"]}formatTemplate(e,t){return e.replace(/\{(\w+)\}/g,(e,i)=>{if(!(i in t))throw new Error(`Missing param: ${i}`);return String(t[i])})}getFullPath(e){if(!e)return e;try{return new URL(e,window.location.href).href}catch{return e}}getCssThemeOption(){const e=this.getAttribute("viewer-css-theme");return Object.keys(n).includes(e)?n[e]:n[a.viewerCssTheme]}applyViewerTheme(){const e=this.getCssThemeOption();(this.iframe.contentWindow?.PDFViewerApplicationOptions)?.set("viewerCssTheme",e);const t=this.iframe.contentDocument;if(!t?.documentElement)return;const i=e===n.LIGHT?"light":e===n.DARK?"dark":"";i?t.documentElement.style.setProperty("color-scheme",i):t.documentElement.style.removeProperty("color-scheme")}appendRuntimeStyle(e){const t=this.iframe?.contentDocument;if(!t?.head||!e)return;if(Array.from(t.querySelectorAll("style")).some(t=>t.textContent===e))return;const i=t.createElement("style");i.setAttribute("data-pdfjs-viewer-runtime-style","true"),i.textContent=e,t.head.appendChild(i)}applyQueuedRuntimeStyles(){this.viewerStyles.forEach(e=>{this.appendRuntimeStyle(e)})}injectScript(e,t="module"){const i=this.iframe.contentDocument;if(!i)return Promise.resolve();if(!i.head){const e=i.createElement("head");i.documentElement?.prepend(e)}return new Promise((r,s)=>{let a="";const n=e=>{a=` (CSP ${e.effectiveDirective||e.violatedDirective||"unknown-directive"} blocked ${e.blockedURI||"unknown-uri"})`},o=()=>{i.removeEventListener("securitypolicyviolation",n)};i.addEventListener("securitypolicyviolation",n);const c=i.createElement("script");c.type=t,c.src=e,c.addEventListener("load",()=>{o(),r()},{once:!0}),c.addEventListener("error",()=>{o(),s(new Error(`Unable to load script: ${e}${a}`))},{once:!0}),i.head?.appendChild(c)})}cleanupLocaleResource(){this.localeResourceLink&&(this.localeResourceLink.remove(),this.localeResourceLink=void 0),this.localeResourceUrl&&(URL.revokeObjectURL(this.localeResourceUrl),this.localeResourceUrl=void 0)}async connectedCallback(){this.iframe=this.shadowRoot?.querySelector("iframe"),this.iframe.setAttribute("title",this.getAttribute("iframe-title")||a.iframeTitle),this.initPromise=(async()=>(await this.buildViewerEntry(),await this.buildViewerApp()))()}disconnectedCallback(){for(this.cleanupLocaleResource(),this.iframe.src="about:blank";this.firstChild;)this.removeChild(this.firstChild)}async attributeChangedCallback(e,t,i){if(t===i)return;if(!this.iframe)return;const r={"debugger-src":{key:"debuggerSrc",fallback:a.debuggerSrc},"c-map-url":{key:"cMapUrl",fallback:a.cMapUrl},"icc-url":{key:"iccUrl",fallback:a.iccUrl},"image-resources-path":{key:"imageResourcesPath",fallback:a.imageResourcesPath},"sandbox-bundle-src":{key:"sandboxBundleSrc",fallback:a.sandboxBundleSrc},"standard-font-data-url":{key:"standardFontDataUrl",fallback:a.standardFontDataUrl},"wasm-url":{key:"wasmUrl",fallback:a.wasmUrl}};if("worker-src"!==e){if(e in r){const t=this.iframe.contentWindow?.PDFViewerApplicationOptions,{key:s,fallback:a}=r[e];return void t?.set(s,i||a)}switch(e){case"src":{const e=this.iframe.contentWindow?.PDFViewerApplication;if(e){await e.initializedPromise;const t=this.getFullPath(i||a.src);t&&e.open({url:t})}return}case"locale":return(this.iframe.contentWindow?.PDFViewerApplicationOptions)?.set("localeProperties",{lang:i||a.locale}),this.cleanupLocaleResource(),await this.injectLocaleData(),await this.applyLocaleAtRuntime()||(this.initPromise=(async()=>(await this.buildViewerEntry(),await this.buildViewerApp()))(),await this.initPromise),void await this.applyIframeHash();case"iframe-title":return void this.iframe.setAttribute("title",i||a.iframeTitle);case"viewer-css-theme":return void this.applyViewerTheme();default:await this.applyIframeHash()}}else(this.iframe.contentWindow?.PDFViewerApplicationOptions)?.set("workerSrc",i||a.workerSrc)}async injectViewerStyles(e){e&&(this.viewerStyles.add(e),this.appendRuntimeStyle(e))}async setViewerOptions(e={}){return this.optionsToSet=e,await this.initPromise,{viewerOptions:this.iframe.contentWindow?.PDFViewerApplicationOptions}}};window.customElements.get("pdfjs-viewer-element")||window.customElements.define("pdfjs-viewer-element",o);export{o as PdfjsViewerElement,o as default,n as ViewerCssTheme};
|
|
1
|
+
var e=new URL("./pdf.worker.min.mjs",import.meta.url).href,t=new URL("./pdf.mjs",import.meta.url).href,i=new URL("./viewer.mjs",import.meta.url).href,r=new URL("./viewer.css",import.meta.url).href,s=new URL("./paper-and-ink.css",import.meta.url).href,h={workerSrc:e,pdfSrc:t,viewerSrc:i,viewerCssSrc:r,themeCssSrc:s},u="PDF viewer window",v="./debugger.mjs",A="../web/cmaps/",S="../web/iccs/",k="./images/",R="../build/pdf.sandbox.mjs",P="../web/standard_fonts/",L="../web/wasm/",j={AUTOMATIC:0,LIGHT:1,DARK:2},D=class extends HTMLElement{constructor(){super(),this.initPromise=Promise.resolve({}),this.viewerStyles=new Set,this.optionsToSet={},this.applyIframeHash=async()=>{const e=this.iframe?.contentWindow;if(!e)return;const t=this.getIframeLocationHash();e.location.hash!==t&&await new Promise(i=>{let r=!1;const s=()=>{r||(r=!0,e.removeEventListener("hashchange",s),i())};e.addEventListener("hashchange",s),e.location.hash=t,queueMicrotask(()=>{e.location.hash===t&&s()})})},this.applyLocaleAtRuntime=async()=>{const e=this.iframe.contentWindow?.PDFViewerApplication,t=this.iframe.contentDocument;if(!e||!t)return!1;await e.initializedPromise;const i=e.externalServices?.createL10n;if("function"!=typeof i)return!1;const r=await i();if(!r)return!1;await(e.l10n?.destroy?.()),e.l10n=r;const s=e.appConfig?.appContainer||t.documentElement;return!!s&&("function"==typeof r.getDirection&&t.documentElement?.setAttribute("dir",r.getDirection()),"function"==typeof r.translate&&await r.translate(s),!0)},this.injectLocaleData=async()=>{const e=this.iframe.contentDocument,t=this.getAttribute("locale");if(!t)return void this.cleanupLocaleResource();const i=await(import("./locale-kKW4I85A.js"));if(!Object.keys(JSON.parse(i.default)).includes(t))return void this.cleanupLocaleResource();const r=this.formatTemplate(this.getAttribute("locale-src-template")||"https://cdn.jsdelivr.net/gh/mozilla-l10n/firefox-l10n@main/{locale}/toolkit/toolkit/pdfviewer/viewer.ftl",{locale:t}),s={[String(t)]:r},n=e.createElement("link");n.rel="resource",n.type="application/l10n",this.cleanupLocaleResource(),this.localeResourceUrl=URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),n.href=this.localeResourceUrl,this.iframe.contentDocument?.head.appendChild(n),this.localeResourceLink=n},this.onViewerAppCreated=()=>new Promise(e=>{const t=this.iframe.contentWindow;if(t.PDFViewerApplication)return e(t.PDFViewerApplication);let i;Object.defineProperty(t,"PDFViewerApplication",{get:()=>i,set(r){i=r,e(r),delete t.PDFViewerApplication,t.PDFViewerApplication=r},configurable:!0})}),this.applyViewerOptions=()=>{const e=this.iframe.contentWindow?.PDFViewerApplicationOptions;e?.set("workerSrc",this.getWorkerSrc()),e?.set("debuggerSrc",this.getAttribute("debugger-src")||v),e?.set("cMapUrl",this.getAttribute("c-map-url")||A),e?.set("iccUrl",this.getAttribute("icc-url")||S),e?.set("imageResourcesPath",this.getAttribute("image-resources-path")||k),e?.set("sandboxBundleSrc",this.getAttribute("sandbox-bundle-src")||R),e?.set("standardFontDataUrl",this.getAttribute("standard-font-data-url")||P),e?.set("wasmUrl",this.getAttribute("wasm-url")||L),e?.set("defaultUrl",this.getFullPath(this.getAttribute("src")||"")),e?.set("disablePreferences",!0),e?.set("eventBusDispatchToDOM",!0),e?.set("localeProperties",{lang:this.getAttribute("locale")||""}),e?.set("viewerCssTheme",this.getCssThemeOption());for(const[t,i]of Object.entries(this.optionsToSet))e?.set(t,i);this.optionsToSet={}},this.getIframeLocationHash=()=>{const e={page:this.getAttribute("page")||"",zoom:this.getAttribute("zoom")||"",pagemode:this.getAttribute("pagemode")||"none",search:this.getAttribute("search")||"",phrase:this.getAttribute("phrase")||"",locale:this.getAttribute("locale")||""};return"#"+Object.entries(e).map(([e,t])=>`${e}=${t}`).join("&")},this.buildViewerEntry=async()=>new Promise(async e=>{const t=await(import("./_virtual_pdfjs-viewer-html-Db40JDMA.js")),i=e=>{try{const t=new URL(e,window.location.href);if("http:"===t.protocol||"https:"===t.protocol)return t.origin}catch{}return""},r=e=>Array.from(new Set(e.filter(Boolean))).join(" "),{pdfSrc:s,viewerSrc:n,viewerCssSrc:a,themeCssSrc:o}=this.getRuntimeFileUrls(),c=i(this.getWorkerSrc()),l=r(["'self'",window.location.origin,i(s),i(n),c]),h=r(["'self'",window.location.origin,i(a),i(o)]),p=["default-src 'none'",`script-src ${l} 'wasm-unsafe-eval'`,`script-src-elem ${l}`,`worker-src ${r(["'self'","blob:",window.location.origin,c])}`,`style-src ${h} 'unsafe-inline'`,`img-src ${h} blob: data:`,"media-src blob:",`font-src ${h} data:`,"connect-src * blob: data:","base-uri 'none'","form-action 'none'"].join("; "),u=t.default.replace(/<meta\s+http-equiv="Content-Security-Policy"[^>]*>/i,`<meta http-equiv="Content-Security-Policy" content="${p};" />`).replace("</head>",`\n <link rel="stylesheet" href="${a}">\n <link rel="stylesheet" href="${o}">\n ${Array.from(this.viewerStyles).map(e=>`<style>${e}</style>`).join("\n")}\n </head>`);this.iframe.addEventListener("load",()=>e(),{once:!0}),this.iframe.srcdoc=u}),this.setupViewerApp=async()=>{const e=await this.onViewerAppCreated();return this.applyViewerOptions(),await(e?.initializedPromise),this.applyViewerTheme(),this.applyQueuedRuntimeStyles(),{viewerApp:e}},this.buildViewerApp=async()=>{await this.applyIframeHash();const e=this.setupViewerApp();await this.injectLocaleData();const{pdfSrc:t,viewerSrc:i}=this.getRuntimeFileUrls();return await this.injectScript(t),await this.injectScript(i),await e},this.attachShadow({mode:"open"}).innerHTML='\n <style>:host{width:100%;display:block;overflow:hidden}:host iframe{height:100%}</style>\n <iframe frameborder="0" width="100%" loading="lazy"></iframe>\n '}static get observedAttributes(){return["src","locale","viewer-css-theme","worker-src","debugger-src","c-map-url","icc-url","image-resources-path","sandbox-bundle-src","standard-font-data-url","wasm-url","page","search","phrase","zoom","pagemode","iframe-title"]}formatTemplate(e,t){return e.replace(/\{(\w+)\}/g,(e,i)=>{if(!(i in t))throw new Error(`Missing param: ${i}`);return String(t[i])})}getFullPath(e){if(!e)return e;try{return new URL(e,window.location.href).href}catch{return e}}getAssetsBase(){const e=this.getAttribute("assets-base")?.trim();return e?this.getFullPath(e.endsWith("/")?e:`${e}/`):""}getRuntimeFileUrls(){const e=this.getAssetsBase();if(!e)return h;const t=t=>{try{return new URL(t,e).href}catch{return`${e}${t}`}};return{workerSrc:t("pdf.worker.min.mjs"),pdfSrc:t("pdf.mjs"),viewerSrc:t("viewer.mjs"),viewerCssSrc:t("viewer.css"),themeCssSrc:t("paper-and-ink.css")}}getWorkerSrc(){return this.getAttribute("worker-src")||this.getRuntimeFileUrls().workerSrc}getCssThemeOption(){const e=this.getAttribute("viewer-css-theme");return Object.keys(j).includes(e)?j[e]:j.AUTOMATIC}applyViewerTheme(){const e=this.getCssThemeOption();(this.iframe.contentWindow?.PDFViewerApplicationOptions)?.set("viewerCssTheme",e);const t=this.iframe.contentDocument;if(!t?.documentElement)return;const i=e===j.LIGHT?"light":e===j.DARK?"dark":"";i?t.documentElement.style.setProperty("color-scheme",i):t.documentElement.style.removeProperty("color-scheme")}appendRuntimeStyle(e){const t=this.iframe?.contentDocument;if(!t?.head||!e)return;if(Array.from(t.querySelectorAll("style")).some(t=>t.textContent===e))return;const i=t.createElement("style");i.setAttribute("data-pdfjs-viewer-runtime-style","true"),i.textContent=e,t.head.appendChild(i)}applyQueuedRuntimeStyles(){this.viewerStyles.forEach(e=>{this.appendRuntimeStyle(e)})}injectScript(e,t="module"){const i=this.iframe.contentDocument;if(!i)return Promise.resolve();if(!i.head){const e=i.createElement("head");i.documentElement?.prepend(e)}return new Promise((r,s)=>{let n="";const a=e=>{n=` (CSP ${e.effectiveDirective||e.violatedDirective||"unknown-directive"} blocked ${e.blockedURI||"unknown-uri"})`},o=()=>{i.removeEventListener("securitypolicyviolation",a)};i.addEventListener("securitypolicyviolation",a);const c=i.createElement("script");c.type=t,c.src=e,c.addEventListener("load",()=>{o(),r()},{once:!0}),c.addEventListener("error",()=>{o(),s(new Error(`Unable to load script: ${e}${n}`))},{once:!0}),i.head?.appendChild(c)})}cleanupLocaleResource(){this.localeResourceLink&&(this.localeResourceLink.remove(),this.localeResourceLink=void 0),this.localeResourceUrl&&(URL.revokeObjectURL(this.localeResourceUrl),this.localeResourceUrl=void 0)}async connectedCallback(){this.iframe=this.shadowRoot?.querySelector("iframe"),this.iframe.setAttribute("title",this.getAttribute("iframe-title")||u),this.initPromise=(async()=>(await this.buildViewerEntry(),await this.buildViewerApp()))()}disconnectedCallback(){for(this.cleanupLocaleResource(),this.iframe.src="about:blank";this.firstChild;)this.removeChild(this.firstChild)}async attributeChangedCallback(e,t,i){if(t===i)return;if(!this.iframe)return;const r={"debugger-src":{key:"debuggerSrc",fallback:v},"c-map-url":{key:"cMapUrl",fallback:A},"icc-url":{key:"iccUrl",fallback:S},"image-resources-path":{key:"imageResourcesPath",fallback:k},"sandbox-bundle-src":{key:"sandboxBundleSrc",fallback:R},"standard-font-data-url":{key:"standardFontDataUrl",fallback:P},"wasm-url":{key:"wasmUrl",fallback:L}};if("worker-src"!==e){if(e in r){const t=this.iframe.contentWindow?.PDFViewerApplicationOptions,{key:s,fallback:n}=r[e];return void t?.set(s,i||n)}switch(e){case"src":{const e=this.iframe.contentWindow?.PDFViewerApplication;if(e){await e.initializedPromise;const t=this.getFullPath(i||"");t&&e.open({url:t})}return}case"locale":return(this.iframe.contentWindow?.PDFViewerApplicationOptions)?.set("localeProperties",{lang:i||""}),this.cleanupLocaleResource(),await this.injectLocaleData(),await this.applyLocaleAtRuntime()||(this.initPromise=(async()=>(await this.buildViewerEntry(),await this.buildViewerApp()))(),await this.initPromise),void await this.applyIframeHash();case"iframe-title":return void this.iframe.setAttribute("title",i||u);case"viewer-css-theme":return void this.applyViewerTheme();default:await this.applyIframeHash()}}else(this.iframe.contentWindow?.PDFViewerApplicationOptions)?.set("workerSrc",i||this.getRuntimeFileUrls().workerSrc)}async injectViewerStyles(e){e&&(this.viewerStyles.add(e),this.appendRuntimeStyle(e))}async setViewerOptions(e={}){return this.optionsToSet=e,await this.initPromise,{viewerOptions:this.iframe.contentWindow?.PDFViewerApplicationOptions}}};window.customElements.get("pdfjs-viewer-element")||window.customElements.define("pdfjs-viewer-element",D);export{D as PdfjsViewerElement,D as default,j as ViewerCssTheme};
|