0

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" 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.

Ali
  • 376
  • 5
  • 16

4 Answers4

2

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

  • embed tag doesn't show up for me! but i can use – Ali Oct 31 '22 at 10:51
1

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

<object data="your/pdf/link" width={yourWidth} height={yourHeight} type="application/pdf" ></object>
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
ArnoVoxel
  • 11
  • 3
  • in my case, I had to use the react-pdf package, but this is another solution to handle it – Ali May 22 '23 at 10:26
0

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.

gsharew
  • 263
  • 1
  • 12
0

i handled my problem by this way :

import { Document,pdfjs, Page } from 'react-pdf';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;



function PDFLayout(props) {
  const [pdfString, setPdfString] = useState("");
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);
  const [PDFBlob, setPDFBlob] = useState();

  const options = {
    cMapUrl: 'cmaps/',
    cMapPacked: true,
    standardFontDataUrl: 'standard_fonts/',
  };


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

return (    
    <div className={classes.main}>
    <div className={classes.pdf_Container}>
          <Document file={pdfString} onLoadSuccess={onDocumentLoadSuccess} error={"لطفا منتظر بمانید"} loading={"wait for load"} onLoadError={console.error} options={options}>
            {Array.from(new Array(numPages), (el, index) => (
              <Page wrap scale={0.65}  className={classes.page}  key={`page_${index + 1}`} pageNumber={index + 1} />
            ))}
          </Document>
    </div>
    </div>

the pdfstring file is loading from a blob file by this way :

  function fetchPDF() {
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer " + token);
    var requestOptions = {
      method: "GET",
      headers: myHeaders,
      redirect: "follow",
    };

    fetch(
      "https://negar-khodro.com/api/Download?filepath=" +
        location.state.Address,
      requestOptions
    )
      .then((response) => response.blob())
      .then((blob) => setPDFBlob(blob))
      .catch((error) => console.log("error", error));
  }

  function loadPDF() {
    console.log(PDFBlob);
    if(PDFBlob !== undefined)
        setPdfString(URL.createObjectURL(PDFBlob));
    }
    

  if (PDFBlob === undefined) fetchPDF();
Ali
  • 376
  • 5
  • 16