将PDF流转为图片展示在页面上
使用 pdfjs-dist 库来渲染 PDF 页面到 canvas 上,然后将 canvas 转为图片
安装 pdfjs-dist
依赖
npm install pdfjs-dist
或者
yarn add pdfjs-dist
创建一个组件来处理 PDF 流的加载和渲染
该组件中是一个包含 PDF 文件的 ArrayBuffer 或者 Uint8Array。
将 pdf 流传入该组件中使用
/** @format */import React, { useState, useEffect } from 'react';
// import { pdfjs } from 'pdfjs-dist';
var pdfjs = require('pdfjs-dist/es5/build/pdf.js');
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;const PdfToImage = ({ pdfData }) => {const [imageSrc, setImageSrc] = useState(null);const base64ToArrayBuffer = (base64) => {var binary_string = window.atob(base64);var len = binary_string.length;var bytes = new Uint8Array(len);for (var i = 0; i < len; i++) {bytes[i] = binary_string.charCodeAt(i);}return bytes.buffer;};useEffect(() => {const renderPDF = async (arrayBuffer) => {const loadingTask = pdfjs.getDocument({ data: arrayBuffer });try {const pdf = await loadingTask.promise;const page = await pdf.getPage(1); // 获取第一页const viewport = page.getViewport({ scale: 1.5 }); // 设置缩放比例const canvas = document.createElement('canvas');const canvasContext = canvas.getContext('2d');canvas.height = viewport.height;canvas.width = viewport.width;const renderContext = {canvasContext,viewport,};await page.render(renderContext).promise;// 将canvas内容转换为图片const imageSrc = canvas.toDataURL('image/png');setImageSrc(imageSrc);} catch (error) {console.error('Error rendering PDF:', error);}};// 首先将base64的PDF流转为ArrayBufferlet arrayBuffer = base64ToArrayBuffer(pdfData);// 然后将ArrayBuffer格式的数据转为图片renderPDF(arrayBuffer);}, [pdfData]);return <div>{imageSrc && <img src={imageSrc} alt="PDF as image" />}</div>;
};export default PdfToImage;
使用示例
这里的PDF_content 也可以直接使用 ArrayBuffer 或者 Uint8Array 的格式,直接传入组件,将组件中的 base64ToArrayBuffer 方法不使用即可。
import React from 'react';
import PdfToImage from './PdfToImage.jsx';render() {const PDF_content = 'XXXX....BYFhEdCmVuZHN0cmVhbQplbmRvYmoKc3RhcnR4cmVmCjg2NTkxCiUlRU9GCg=='// base64 格式return (<PdfToImage pdfData={PDF_content}></PdfToImage>)}