将PDF流展示在页面上
使用 pdfjs-dist 库来渲染 PDF 页面到 canvas 上进行绘制展示
安装 pdfjs-dist
依赖
npm install pdfjs-dist
或者
yarn add pdfjs-dist
创建一个组件来处理 PDF 流的加载和渲染
该组件中是一个包含 PDF 文件的 Base64。
将 pdf 流传入该组件中使用
/** @format */import React, { useState, useEffect, useRef } from 'react';
var pdfjsLib = require('pdfjs-dist/es5/build/pdf.js');
// eslint-disable-next-line import/first
import 'pdfjs-dist/es5/build/pdf.worker.entry';const PdfViewer = ({ url, id }) => {const [pageNumbers, setPageNumbers] = useState(0);const [currentPage, setCurrentPage] = useState(1);const [loading, setLoading] = useState(true);const [rendering, setRendering] = useState(false);const pdfRef = useRef(null);function renderPdf(pdfFile) {let canvas = document.getElementById(id);let canvasContext = canvas.getContext('2d');pdfFile.getPage(currentPage).then((page) => {//逐页解析PDFvar viewport = page.getViewport({ scale: 5 }); // 页面缩放比例,值越大越清晰canvas.height = viewport.height;canvas.width = viewport.width;canvasContext.clearRect(0, 0, canvas.width, canvas.height);var renderContext = {canvasContext: canvasContext,viewport: viewport,rotate: 90,};setRendering(true);page.render(renderContext).promise.finally(() => {setRendering(false);}); //渲染生成});}useEffect(() => {let loadingTask = pdfjsLib.getDocument({url: url,//cMapUrl: './cmaps/',//cMapPacked: true,});loadingTask.promise.then((pdf) => {// console.log(pdf.numPages);pdfRef.current = pdf;setPageNumbers(pdf.numPages);renderPdf(pdf);}).catch((error) => {console.log(error);}).finally(() => {setLoading(false);});}, []);useEffect(() => {if (pdfRef.current) {window.scrollTo({ top: 0 });renderPdf(pdfRef.current);}}, [currentPage]);return (<div><canvas id={'pdf' + id} style={{ width: '100%' }} /></div>);
};export default PdfViewer;
使用示例
import React from 'react';
import PdfViewerfrom './PdfViewer.jsx';render() {const url= 'XXXX....BYFhEdCmVuZHN0cmVhbQplbmRvYmoKc3RhcnR4cmVmCjg2NTkxCiUlRU9GCg=='// base64 格式return (<PdfViewer id={'pdf_file'} url={`data:application/pdf;base64,${url}`}></PdfViewer>)}
使用问题
在使用的过程中,有一个项目是可以的,但是另一个项目会报错,如下图: