简体   繁体   English

React中如何引用pdf.js库?

[英]How to reference pdf.js library in React?

I am trying to reference PDF.js (by Mozilla) into my React project.我正在尝试将PDF.js (由 Mozilla)引用到我的 React 项目中。 However, it is throwing 'Unexpected identifier' error.但是,它抛出“意外标识符”错误。

I have placed the PDF.js in the public folder and referenced it in my index.html.我已将 PDF.js 放在公共文件夹中,并在我的 index.html 中引用它。

File structure:文件结构:

public
  - index.html
  - pdftojs
    - parsejs.js // < parseFile method in this file will be called
    - pdf-parse.js
    - misc..
src
  - pdftotext
    - parsepdf.js // < page to parse PDF

pdf-parse.js pdf-parse.js

var PDFJS = null
function render_page(pageData) { ... } // Untouched
async function PDF(...) { ... } // Untouched

exports.pdf = PDF; // Changed this line

parsejs.js from the original library:来自原始库的 parsejs.js:

8    import pdf from 'pdf-parse.js';
9    const pdfjsLib = require('pdfjs-dist'); // 'require' is undefined too so I don't know what is the correct way
10    
11   function parseFile(file) {

... 
45   }

This file throws Unexpected identifier on Line 8此文件Unexpected identifier on Line 8

Parse PDF Page (parsepdf.js)解析 PDF 页面 (parsepdf.js)

  process(file) {
     parseFile(file); // calling method in parsejs.js
     ...
  }

which gives 'parseFile' is not defined这给出了'parseFile' is not defined

I spent too much time today, piecing together fragments of other answers to this question.我今天花了太多时间,把这个问题的其他答案的片段拼凑起来。 So here is a complete answer.所以这是一个完整的答案。

First you install pdfjs-dist:首先安装pdfjs-dist:

npm install pdfjs-dist

And here is how to use it in an actual viewer component:以下是如何在实际查看器组件中使用它:

import React, { useEffect, useState, useRef, useCallback } from 'react';
import pdfjsLib from "pdfjs-dist/build/pdf";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

export default function PdfViewer({url}){
  const canvasRef = useRef();
  pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;

  const [pdfRef, setPdfRef] = useState();
  const [currentPage, setCurrentPage] = useState(1);

  const renderPage = useCallback((pageNum, pdf=pdfRef) => {
    pdf && pdf.getPage(pageNum).then(function(page) {
      const viewport = page.getViewport({scale: 1.5});
      const canvas = canvasRef.current;
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      const renderContext = {
        canvasContext: canvas.getContext('2d'),
        viewport: viewport
      };
      page.render(renderContext);
    });   
  }, [pdfRef]);

  useEffect(() => {
    renderPage(currentPage, pdfRef);
  }, [pdfRef, currentPage, renderPage]);

  useEffect(() => {
    const loadingTask = pdfjsLib.getDocument(url);
    loadingTask.promise.then(loadedPdf => {
      setPdfRef(loadedPdf);
    }, function (reason) {
      console.error(reason);
    });
  }, [url]);

  const nextPage = () => pdfRef && currentPage < pdfRef.numPages && setCurrentPage(currentPage + 1);

  const prevPage = () => currentPage > 1 && setCurrentPage(currentPage - 1);

  return <canvas ref={canvasRef}></canvas>;
}

此导入将清除未定义的问题:

import * as pdfjsLib from "pdfjs-dist/build/pdf";

checkout these examples from installing Pdf.js from webpack.通过从 webpack 安装 Pdf.js 来查看这些示例。

pdf.js pdf.js

Then this is how you reference and bring in the information into your own project.然后,这就是您引用信息并将其引入您自己的项目的方式。

    import pdfjsLib from 'pdfjs-dist/webpack';

我无法启动我的应用程序,直到我安装了以前版本的 npm 模块 npm i pdfjs-dist@2.6.347

   <PDFDownloadLink
          document={
            <PDFReport
              key={report.id}
              report={report}
              account={account}
              user={user}
              isFullPageImage={toggle}
              includeImages={includeImages}
              I18n={I18n}
            />
          }
          fileName={`${report.name}.pdf`}
        >
          {({ blob, url, loading, error }) => {
            console.log('error', error)
            console.log('loading', loading)
            console.log('blob', blob)
            console.log('url', url)

            return loading ? (
              <SpinnerDiv>
                <Spinner />
              </SpinnerDiv>
            ) : (
              <LinkContainer>
                <PdfIcons src={pdf} />
                <p style={{ fontSize: '2rem', fontWeight: 600 }}>
                  {I18n.t('report_download_pdf_button')}
                </p>
              </LinkContainer>
            )
          }}
        </PDFDownloadLink>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM