请使用这个库
https://www.npmjs.com/package/react-pdf-to-image
这很简单。它将返回图像列表(pdf中的每一页作为一个图像)
import React from 'react';
import {PDFtoIMG} from 'react-pdf-to-image';
import file from './pdf-sample.pdf';
const App = () =>
<div>
<PDFtoIMG file={file}>
{({pages}) => {
if (!pages.length) return 'Loading...';
return pages.map((page, index)=>
<img key={index} src={page}/>
);
}}
</PDFtoIMG>
</div>
export default App;
如果您只想将每个 pdf 页面下载为图像而不是组件,请遵循以下代码
import PDFJS from 'pdfjs-dist/webpack';
这是 react-pdf-to-image 的依赖库。然后阅读pdf文件(我将base64作为输入)
PDFJS.getDocument(blob).promise.then(pdf => {
const pages = [];
this.pdf = pdf;
for (let i = 0; i < this.pdf.numPages; i++) {
this.getPage(i + 1).then(result => {
// the result is the base 64 version of image
});
}
})
阅读完每一页后,从 getPage 方法中读取每一页作为图像,如下所示
getPage = (num) => {
return new Promise((resolve, reject) => {
this.pdf.getPage(num).then(page => {
const scale = "1.5";
const viewport = page.getViewport({
scale: scale
});
const canvas = document.createElement('canvas');
const canvasContext = canvas.getContext('2d');
canvas.height = viewport.height || viewport.viewBox[3]; /* viewport.height is NaN */
canvas.width = viewport.width || viewport.viewBox[2]; /* viewport.width is also NaN */
page.render({
canvasContext, viewport
}).promise.then((res) => {
resolve(canvas.toDataURL());
})
})
})
}