React 项目中安装和使用 mozilla/pdf.js

31 min read

说明:您需要先安装 Node.js 和 React,并确保您已经在项目目录下。

  1. 在项目目录下安装 pdfjs-dist

可以使用 npm 或者 yarn 安装:

使用 npm:

npm install pdfjs-dist --save

使用 yarn:

yarn add pdfjs-dist
  1. 将 PDF 页面渲染到 React 组件中

您需要在 React 组件中使用 pdfjs-dist 模块将 PDF 页面渲染为 canvas 元素:

import React, { useEffect } from 'react';
import pdfjsLib from 'pdfjs-dist';

const PdfViewer = () => {
  useEffect(() => {
    const canvas = document.getElementById('pdf-canvas');
    const pdfUrl = 'http://example.com/example.pdf';
    pdfjsLib.getDocument(pdfUrl).promise.then((pdf) => {
      pdf.getPage(1).then((page) => {
        const viewport = page.getViewport({ scale: 1 });
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        const renderContext = {
          canvasContext: context,
          viewport,
        };
        page.render(renderContext);
      });
    });
  }, []);

  return (
    <div>
      <canvas id="pdf-canvas" />
    </div>
  );
};

export default PdfViewer;

上面的代码中,我们使用 useEffect 来处理异步事件,然后使用 pdfjsLib 模块加载 PDF 文件。

pdf.getDocument(url) 方法会返回一个 Promise,然后我们获取第一页并将其渲染到 canvas 上。

在渲染过程中,我们需要获取页面的 viewport,然后将 canvas 元素的高度和宽度设置为 viewport 的高度和宽度。

  1. 运行 React 项目

使用以下命令运行 React 项目:

使用 npm:

npm start

使用 yarn:

yarn start

现在,您可以在 React 项目中查看 PDF 文件了。