我正在尝试将PDF.js(由Mozilla引用)到我的React项目中。但是,它将引发“意外的标识符”错误。
我已将PDF.js放置在公用文件夹中,并在index.html中对其进行了引用。
文件结构:
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
var PDFJS = null
function render_page(pageData) { ... } // Untouched
async function PDF(...) { ... } // Untouched
exports.pdf = PDF; // Changed this line
原始库中的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 }
此文件引发Unexpected identifier on Line 8
解析PDF页面(parsepdf.js)
process(file) {
parseFile(file); // calling method in parsejs.js
...
}
给出'parseFile' is not defined
答案 0 :(得分:2)
此导入将清除未定义的问题:
import * as pdfjsLib from "pdfjs-dist/build/pdf";
答案 1 :(得分:1)
我今天花了太多时间,把这个问题的其他答案的片段拼凑在一起。因此,这是一个完整的答案。
首先安装pdfjs-dist:
npm install pdfjs-dist
以下是在实际查看器组件中的使用方法:
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>;
}
答案 2 :(得分:0)