PDF.js Express files can be served and loaded from a CDN or another origin. However, a few tweaks are required to make this work due to browser security restrictions.
View sample1) Copy assets to CDN
The first step is to copy the correct assets to your CDN.
All of the files located in node_modules/@pdftron/pdfjs-express/public
need to be copied.
Also, you need to add the origin of your application to the node_modules/@pdftron/pdfjs-express/public/ui/configorigin.txt
file. This is required to work around CORS problems related to iFrames.
2) Load the static assets
After the files are on the CDN, you tell Express to load those files by setting the path
parameter to point to the location of those files:
import WebViewer from '@pdftron/pdfjs-express'
WebViewer({
path: "https://my-cdn.com/pdfjs-express/public"
})
Note: When loading PDF.js Express cross origin, the WebViewer function will NOT resolve with the WebViewer instance. Instead, you need to use a config file to access WebViewer APIs. See below for details.
3) Set up the config file
In order to access WebViewer apis, you need to create a config file.
A config file is just a Javascript file that gets executed in the context of the iFrame.
For example, you config file could look like this:
// config.js
window.addEventListener('viewerLoaded', () => {
instance.UI.loadDocument('https://pdftron.s3.amazonaws.com/downloads/pl/webviewer-demo.pdf')
})
Once your config file is set up, you can upload that to your CDN as well.
Now, tell WebViewer the location of the config file like so:
import WebViewer from '@pdftron/pdfjs-express'
WebViewer({
path: "https://my-cdn.com/pdfjs-express/public",
config: "https://my-cdn.com/pdfjs-express/config.js"
})
4) Passing data between windows
Since the iFrame is loaded from another origin, you cannot directly access functions or DOM elements inside the iFrame due to browser security rules.
However, you may use the postMessage API to pass data back and forth between windows.
This flow is outlined in our sample.