Search code examples
javascriptreactjspdfreact-pdf

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.


Solution

  • 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