react-pdf Package

  • React-PDF is a popular library for rendering PDF documents in a React application. It provides a range of components and APIs to help you display PDF files, including pages, annotations, and text selection.
  • The main component provided by React-PDF is the Document component, which represents a PDF file. Once the Document component has been loaded, you can use other components provided by React-PDF to display the PDF content.
Here are the steps to install the react-pdf package in a React application:
  • Open a terminal or command prompt window in your project directory.
  • Install the react-pdf package using npm or yarn, by running one of the following commands:
  • Using npm:

    npm install react-pdf

  • Using yarn:

    yarn add react-pdf

  • Wait for the installation to finish. This may take a few minutes, depending on your internet speed and the size of your project.
  • Once the installation is complete, you can import the react-pdf components in your React application. For example, to use the Document and Page components, you can import them like this:

  import React, { useState, useEffect } from "react"
  import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
  import 'react-pdf/dist/esm/Page/TextLayer.css';
  import { Document, Page, pdfjs } from "react-pdf";
  import pwd from "./pwd.pdf"
  import doc from "./document.pdf"
  // pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`
  pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

  function App() {

    const pdfUrl = "https://www.upes.ac.in/media/8553/sob-digi.pdf"
    // const pdfUrl = "https://mag.wcoomd.org/uploads/2018/05/blank.pdf"
    // const pdfUrl = ""
    // const pdfUrl = doc
    // const pdfUrl = pwd
    const [numPages, setNumPages] = useState(null);
    const [pageNumber, setPageNumber] = useState(1);
    const [progress, setProgress] = useState(0)
    let mystr = ""
    function onDocumentLoadSuccess({ numPages }) {
      mystr = ""
      setNumPages(numPages);
    }

    return (<>
      <div style={{ display: "flex" }}>
        <Document
          file={pdfUrl}
          error={() => {
            return (<>
              <h1>Error when rendering doc.</h1>
            </>)
          }}
          onLoadSuccess={onDocumentLoadSuccess}
          onLoadProgress={({ total, loaded }) => {
            const progress = total > 0 ? Math.floor((loaded / total) * 100) : 0;
            setProgress(progress)
          }}
          loading={() => {
            return (<>
              <h3>
                loading...{progress}
              </h3>
            </>)
          }}
          noData={(e) => {
            // when pdfUrl is empty
            return (<>
              <h1>No pdf source available</h1>
            </>)
          }}
          onLoadError={(error) => alert('Error while loading document! ' + error.message)}
          onPassword={(callback) => {
            const t1 = prompt("Enter Your Password", "Write Here...")
            callback(t1)
          }}
          rotate={0}
        >
          <Page
            // canvasBackground="black"
            // customTextRenderer={({ str, itemIndex }) => str.replace(/What/g, value => `<mark>${value}</mark>`)}
            // customTextRenderer={({ str, itemIndex }) => {
            //   mystr = mystr.concat(`${str} `)
            //   console.log("itemIndex", itemIndex)
            // }}
            error={() => {
              return (<>
                <h1>Error when rendering doc.</h1>
              </>)
            }}
            // height={500}
            // width={400}
            // scale={1}
            loading={() => {
              return (<>
                <h3>
                  loading...{progress}
                </h3>
              </>)
            }}
            noData={(e) => {
              // when pdfUrl is empty
              return (<>
                <h1>No pdf source available</h1>
              </>)
            }}
            onLoadError={(error) => {
              alert('Error while loading document! ' + error.message)
            }}
            // onLoadSuccess={(page) => {
            //   console.log("object", page.pageNumber)
            // }}
            // renderTextLayer={false}
            pageNumber={pageNumber}
          />
        </Document>

        <div style={{ margin: "20px" }}>
          <p>
            Page {pageNumber} of {numPages}
          </p>
          <button
            type="button"
            onClick={() => {
              if (numPages > pageNumber) {
                setPageNumber(pageNumber + 1)
              }
            }}
          >Next Page</button>
          <br />
          <br />
          <button
            type="button"
            onClick={() => {
              if (pageNumber > 1) {
                setPageNumber(pageNumber - 1)
              }
            }}
          >Previous Page
          </button>
        </div>
      </div>
    </>);
  }

  export default App

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...