I am using react-pdf to show pdf file in my app.
I have so many pdf url on a download server and they are completely public.
here is a link of my pdfs: https://virafiles.ir/books/103/103.pdf.
I can load it in <iframe>
, in browser and so on.
My problem is with react-pdf and <Document />
component. I checked the reference https://github.com/wojtekmaj/react-pdf/wiki/Frequently-Asked-Questions#when-im-trying-to-load-a-pdf-file-from-an-external-source-im-given-a-message-failed-to-load-pdf-file
and I still stucked.
my error is :
Access to fetch at 'https://virafiles.ir/books/103/103.pdf' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
here is my component:
<Document
file={pdf}
onLoadSuccess={onDocumentLoadSuccess}
loading={STATIC_MESSAGES.INFO.loading}
error={STATIC_MESSAGES.ERROR.server}
noData={STATIC_MESSAGES.ERROR.server}>
<PDFPage
curPage={curPage}>
</PDFPage>
</Document>
Also, I try to add Allow-access-origin
in .htaccess
of my download server or some code like this:
<FilesMatch "\.(pdf)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.example|dev02.otherdomain.example)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header merge Vary Origin
</IfModule>
</FilesMatch>
furthermore, I try to using fetch for pdf and then blob it or use PHP to read file but I still stuck in CORS error.
here is my fetch:
const GetPDF = async function (url: string) {
const fetchParams: RequestInit = {
mode: "no-cors",
headers: {
Accept: "application/pdf",
},
}
return fetch(url, fetchParams)
.then(response => response.blob())
.then(respond => window.URL.createObjectURL(respond))
.catch(err => {
throw err
})
}
if (!pdfUrl) return
const res = await GetPDF(pdfUrl)
setPdf(pdfUrl)
dispatch(setCurrentPage(1))