0

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))


Amirhoseinh73
  • 409
  • 5
  • 14
  • @amirhoseih73 any workaround for this ? I am facing same issue – Zahra Aug 01 '23 at 13:09
  • Yes, the problem was from our download server, when I tried to change .htaccess, I didn't access to restart apache and I think the problem was that. I told administrators of download server and they fix the issue and didn't explain that problem was from restarting apache or something else. I hope you can fix the issue. – Amirhoseinh73 Aug 01 '23 at 23:49
  • I forgot to mention. @Zahra – Amirhoseinh73 Aug 01 '23 at 23:57

0 Answers0