CORS and PDF not loading!

The PDF file that you have set to your PDF viewer may not load and can be prevented by many causes. We will discuss some of them here:

– Related messages: CROSS ORIGIN!! Error: Cannot access file! –

CORS: #

Note: CORS access settings/solution may not be available for servers like Google Drive, One Drive, or other file sharing services. They do so to protect their bandwidth. These solutions are possible for servers that are owned by the customers or have access to such settings.

CORS(Cross-Origin Resource Sharing) is common when files are in one domain and site/page is in another domain. Happens commonly with CDNs. Modern browser security has gotten stricter and file success between different protocols and domains are restricted by default.

DearPDF uses PDF.js that relies on Ajax requests to fetch PDF files and then render them using HTML5. This is where CORS applies when the PDF file and page, where PDF viewer is added, are in different protocol or domain. You can check if the following conditions are met to see if you have such a situation:


CORS due to improper HTTPS configuration: #

This is a result of improper https redirection. We recommend using the proper setup to redirect every HTTP request to https to avoid any conflict.

In this case, domain can be in https:// and the PDF file can be in http:// , or ice- versa, which causes CORS. Make sure any pages, files that are requested through http is redirected to https.


CORS due to multiple domain usage: #

If you are using the file from another domain, make sure you have a proper CORS setup done in another domain. Example: PDF viewer page is in abcd.com while the PDF files is from xyz.com


CORS Fix – Apache : #

For Apache Server, add following lines in .htaccess file

Header set Access-Control-Allow-Origin "*" 
Header set Access-Control-Allow-Headers "Range" 
Header set Access-Control-Expose-Headers: "Accept-Ranges, Content-Encoding, Content-Length, Content-Range"

More Info: https://enable-cors.org/server.html


CORS Fix – Amazon Web Servers (AWS) #

Use the following settings in CORS configuration in your AWS bucket. Newer instances use JSON settings.

[
    {
        "AllowedHeaders": [],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

For older instances use XML setting:

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
   <AllowedHeader>*</AllowedHeader>
   <MaxAgeSeconds>3000</MaxAgeSeconds>
 </CORSRule>
</CORSConfiguration>

More Info: https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html


CORS Fix – Buddy CDN #

Goto Pull Zones -> Headers -> Add CORS Headers. Just add, js and pdf in the Extension list.

Leave a Reply

Your email address will not be published.