Kenny John Jacob
Kenny John Jacob

Reputation: 1198

React embedding PDF using react-pdf not working

I'm trying to use react-pdf to render a pdf document. I have a react app generated by create-react-app. I have followed the instructions mentioned in the github readme for CRA (https://github.com/wojtekmaj/react-pdf#create-react-app).

import { Document, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

I have placed a sample PDF file in ./public/dummy.pdf.

enter image description here

And it is accessible at enter image description here

I am using the Document component as below but nothing gets rendered on the page.

<Document file="http://localhost:3000/dummy.pdf" />

enter image description here

This is what it looks like in React DevTools for Chrome enter image description here

What am I missing?

Upvotes: 2

Views: 5212

Answers (1)

Bless
Bless

Reputation: 5370

Document component mostly deals with fetching the PDF and managing loading/error states. To render the pages of the PDF, you need to render Page component passing the corresponding page number.

Slightly modified version of the example taken from Usage section to render all pages of the PDF:

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

function MyApp() {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

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

  return (
    <div>
      <Document
        file="dummy.pdf"
        onLoadSuccess={onDocumentLoadSuccess}
      >
        {[...Array(numPages).keys()].map((p) => (
          <Page pageNumber={p + 1} />
        ))}
      </Document>
    </div>
  );
}

Upvotes: 5

Related Questions