pdfjs-dist
js
const [pdfNum, setPdfNum] = useState(0)
const pdf = require('pdfjs-dist')
pdf.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry')
pdf
.getDocument(fileUrl)
.promise.then((pdfDocument) => {
setPdfNum(pdfDocument.numPages)
for (let i = 1; i <= pdfDocument.numPages; i++) {
pdfDocument.getPage(i).then((pdfPage) => {
const vp = pdfPage.getViewport({ scale: 1.0 })
const viewport = pdfPage.getViewport({ scale: window.innerWidth / vp.width })
const canvas: any = document.getElementById('canvasDom' + i)
if (!canvas) {
return Promise.reject()
}
canvas.width = viewport.width
canvas.height = viewport.height
const ctx = canvas.getContext('2d')
const renderTask = pdfPage.render({
canvasContext: ctx,
viewport,
})
return renderTask.promise
})
}
})
.catch((err) => {
console.log(err)
})
tsx
new Array(pdfNum)
.fill(0)
.map((item, index) => <canvas id={'canvasDom' + (index + 1)} key={index} />)
2.4版本以上就不兼容苹果和chrome之外的浏览器了,建议降低版本到2.2.228
如果打包时候出现了webpack5的问题,建议在alias里面配置上"url":require(‘/url’)
作者还将pdfjs-dist封装成一个组件 感兴趣的可以看下
封装一个react pdf插件