The previous post has introduced how to disable the CORS (Cross-Origin Resource Sharing) of PDF.js, but PDF.js still cannot load the file from the URL, this is because the double CORS block of PDF.js and the browser. This post will figure out: ① How to bypass the browser CORS to load file with URL? ② How to load URL file using PDF.js?
Keywords: browser , CORS , website , PDF.js , load file from url.
Browser CORS
After we disabled the CORS verification code in viewer.js, we will find that PDF.js still cannot load the URL file correctly, and the error message becomes: “Message: Failed to fetch”, which means that our URL file restricted. It is also possible that the address of the document is wrong.
The error reported here is due to the block of the browser CORS. At this time, when you open the browser DevTools (F12 or Fn+F12), you can see the error message in the console : Access to XMLHttpRequest at ‘file:///C:/Programmer/pdfjs-2.4.456-dist/web/locale/locale.properties’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

error message
Bypass browser CORS
Point to the problem of block browser CORS in loading URL file, on solution is that the server converting PDF file into a stream and render it to PDF.js, but we will not discuss such a strategy here, we care how to solve this problem only in the website. To solve this problem needs the following steps. The following files viewer.js, viewer.html and test.html are in pdfjs-2.4.456-dist\web.
Modify viewer.js
Disable the following code in viewer.js, then override the functions for loading PDF file named webViewerLoad and Run.
inactivate code
rewrite webViewerLoad
Modify viewer.html
Add a function in viewer.html to call the modified webViewerLoad function when viewer.html onloading.
add webViewerLoad
Dynamically load PDF
Modify the function in viewer.html to load the file according to the PDF url parameter carried in the <iframe> src.
modify viewer.html onload
When using <iframe> in test.html to refer to the viewer.html of PDF.js, you only need to modify the PDF URL after src=”viewer.html?file=”. That is, changing the src attribute of <iframe> to realize dynamic loading of PDF file.
complete test.html
Summarize
PDF.js cannot open files by URL, which limits our usage, so we have to override some functions. The main changes are as follows:
This post introduces how to load PDF files from URLs in PDF.js. If you want to know how to use PDF.js to get the contents of PDF files and manipulate pdf file with code, please view the related post.