Ali
Ali

Reputation: 421

loading pdf file in react application

I'm trying to show a pdf file with react-pdf package that is installed using npm

import { Document, Page, pdfjs } from "react-pdf";
import { useState } from "react";
import React from "react";

function PDFLayout(props){
  pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }

  return (
    <div>
   // the file address is temporary and just for test 
    <Document  file="https://www.orimi.com/pdf-test.pdf" onLoadSuccess={onDocumentLoadSuccess}>
      <Page pageNumber={pageNumber} />
    </Document>
    <p>
      Page {pageNumber} of {numPages}
    </p>
  </div>

  );
}
export default PDFLayout;

and when i route to this react file i get this error:

Failed to load pdf file

i checked other Question in SO and GH like :

but the answers didn't work for me. so I'm really appreciative of all the help you will give to me.

Upvotes: 0

Views: 3625

Answers (3)

ArnoVoxel
ArnoVoxel

Reputation: 23

It's also possible to use the HTML tag, <object>:

<object data="your/pdf/link" width={yourWidth} height={yourHeight} type="application/pdf" ></object>

Upvotes: 1

Animesh Mondal
Animesh Mondal

Reputation: 106

instead of using a package you can embbed a pdf using the following code

<div class="embed-responsive" style={{ height: "100vh" }}>
        <embed
          src="https://www.orimi.com/pdf-test.pdf"
          type="application/pdf"
          width="100%"
          height="100%"
        />
</div>

It will open the browser's pdf viewer directly into your div

Upvotes: 4

gsharew
gsharew

Reputation: 283

This is because due to the CORS policy, let look the image below.enter image description here

So, this time you need to add a header to your server, to allow CORS policy.

Upvotes: 0

Related Questions