2

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?

1 Answer 1

5

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>
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

So we need to go through it page by page, or does all pages get rendered?
If you want to render all pages of the PDF, you need to render Page component for each page passing the page number as prop.
Great, I'll give it a try! Thanks ☺️
Make sure to visit Recipes wiki, often overlooked part of React-PDF documentation, which handles most popular use cases: github.com/wojtekmaj/react-pdf/wiki/Recipes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.