i created my react app by create-react-app and i'm trying to show a pdf file with react-pdf package. i installed react pdf using npm install react-pdf and used it in code as below:
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" onl oadSuccess={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 :
-
So, this time you need to add a header to your server, to allow CORS policy.
CodePudding user response:
instead of using a package you can embbed a pdf using the following code
<div 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