Bootstrap

【react-pdf】实现在线pdf加载——翻页加载和下拉滚动加载

react-pdf插件地址

一、安装插件

$ npm install react-pdf 
# or
$ yarn add react-pdf

二、组件引用

import { Document, Page } from "react-pdf";

三、简单使用

file可以是 URL、base64 内容、Uint8Array 等;

import { useState } from "react";
import { Document, Page } from "react-pdf";
import pdfFile from '../../../assets/探索自然之美_20250107105901.pdf'

const PdfOperate = () => {
  const [numPages, setNumPages] = useState<number>();
  const [pageNumber] = useState<number>(1);

  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
    setNumPages(numPages);
  }

  return (
    <div>
      <Document file={pdfFile} onLoadSuccess={onDocumentLoadSuccess}>
        <Page pageNumber={pageNumber} />
      </Document>
      <p>
        Page {pageNumber} of {numPages}
      </p>
    </div>
  );
};

export default PdfOperate;

在这里插入图片描述

四、实现简单的上一页 / 下一页翻页加载

<Button onClick={handlePreviousPage}>上一页</Button>
<Button onClick={handleNextPage}>下一页</Button>
 
 const handlePreviousPage = () => {
    if (pageNumber > 1) {
      setPageNumber(pageNumber - 1);
    }
  };
 const handleNextPage = () => {
   if (pageNumber < numPages) {
     setPageNumber(pageNumber + 1);
   }
 };

五、实现简单的下拉滚动加载

下拉滚动加载完整代码:

import React, { useState } from "react";
import { pdfjs } from "react-pdf";
import { Document, Page } from "react-pdf";
import "react-pdf/dist/Page/AnnotationLayer.css";
import "react-pdf/dist/Page/TextLayer.css";
import pdfUrl from "../../../assets/探索自然之美_20250107105901.pdf";

type PDFFile = string | File | null;

const maxWidth = 800;

const options = {
  cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
  standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
};

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

export default function CeshiOperate() {
  const [file] = useState<PDFFile>(pdfUrl);
  const [numPages, setNumPages] = useState<number | undefined>();
  const [containerWidth] = useState<number>(800);

  const onDocumentLoadSuccess = ({ numPages }: { numPages: number }): void => {
    setNumPages(numPages);
  };


  return (
    <div>
      <Document
        file={file}
        onLoadSuccess={onDocumentLoadSuccess}
        options={options}
      >
        {Array.from(new Array(numPages), (el, index) => (
          <Page
            key={`page_${index + 1}`}
            pageNumber={index + 1}
            width={
              containerWidth ? Math.min(containerWidth, maxWidth) : maxWidth
            }
          />
        ))}
      </Document>
    </div>
  );
}

不同的点也就是在这里对当前的numpages页进行了遍历。numPages是总页数,设置唯一标识key,也可以用index。

这里是我的一个简单使用,详解可看点击上方查看react-pdf插件地址的一些其他用法;

;