The previous posts introduced why you should choose PDF.js and how to import PDF.js into your own project. Through the previous steps, we can open local file in PDF.js, but when we want to load file from URL, it will be failed because of blocking the CORS(Cross-Origin Resource Sharing). Through this post, you will learn: ① How to modify the default file opened by PDF.js? ② How to modify PDF.js so that it can load file from URL? ③ How to figure out the CORS block problem for load file from URL?
Keywords: PDF.js , CORS , CORS block , load file from url.
Default file
The PDF.js I used in this post is the release version of pdfjs-2.4.456-dist. To ensure that your experiments have the same effect as mine, it is recommended to choose the same version. If you don’t have this version of the file, you can email me to get it (libertynlp@163.com).
Folder structure
Every time you open PDF.js, the file named compressed.tracemonkey-pldi-09.pdf in pdfjs-2.4.456-dist/web is loaded by default. So, how can we change the files that are loaded by default? Before solving this problem, let’s review the directory structure of pdfjs-2.4.456-dist to make the following description clearer. The figure below only shows the files that will be modified in this blog.

pdfjs-2.4.456-dist
Modify defalult
To modify the file opened by default in PDF.js, you need to search in web\viewer.js and modify the value of the defaultUrl parameter, change defaultUrl to the file you want to open by default, but if you change it to load the file from the URL, it is possible be failed and the next section will give you specific solutions. At least, we can specify any local file as the default open file now.
Load URL file
When we want to load a document from a URL, it will be interrupted by encountering CORS block, and it will be PDF.js and browsers (such as Chrome) two-stage CORS block that cause loading file failure.
Considering that this post should not be too long, the left content will only give a solution for the CORS block caused by of PDF.js itself, and the solution for the browser is placed into another POST, please see related articles to see it.
PDF.js CORS block
When I changed the defaultUrl to the following value, PDF.js returned me an error : “Message: file origin does not match viewer’s”, which means that the pdf file we are using triggers the CORS block of PDF.js.

PDF.js error
Inactivate PDF.js CORS
CORS guarantees the security of our application to the greatest extent, but it also limits our usage. To avoid being affected by PDF.js CORS, you need to inactivate the following code in the viewer.js, that is, make it invalid.
Summarize
The file cannot be loaded from URL in PDF.js. This is because the double CORS of PDF.js and the browser restricts us. This POST introduces how to release the CORS of PDF.js. As for how to release the CORS of the browser, please read the related article.