react项目中预览pdf文件
最近需求,要在b端展示上传的pdf文件。实现方式有很多,记录一下我们最常用的pdf.js
//安装 "pdfjs-dist": "2.0.402" //引入 import * as pdfjs from 'pdfjs-dist' import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry' // 定义初始值 let pdfDoc = null;
const [pdfParams, setPdfParams] = useState({
pageNumber: 1, // 当前页
total: 0,// 总页数
});
// 预览pdf文档的地址 let pdfUrl = 'https://c.alisports.com/xxxxx/test.pdf' // 加载 useEffect(() => { loadPdfFile(pdfUrl); }, [pdfUrl]); // 初始化 const loadPdfFile = (pdfUrl) => { pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker ; let url = pdfUrl ; pdfjs.getDocument(url).promise.then(async (doc) => { pdfDoc = doc getPdfPage(1) setPdfParams(s => ({ ...s, total: doc.numPages })) }) } //加载页数 const getPdfPage = (number) => { pdfDoc.getPage(number).then(page => { const viewport = page.getViewport() const canvas = document.getElementById('pdf-render') const context = canvas.getContext('2d') canvas.width = viewport.viewBox[2] canvas.height = viewport.viewBox[3] viewport.width = viewport.viewBox[2] viewport.height = viewport.viewBox[3] canvas.style.width = viewport.width // viewport.width为pdf文件的实际宽度 canvas.style.height = viewport.height // viewport.height为pdf文件的实际高度 let renderContext = { canvasContext: context, viewport: viewport, // 这里transform的六个参数,使用的是transform中的Matrix(矩阵) transform: [1, 0, 0, -1, 0, viewport.height] // 默认填这个就好了 } // 进行渲染 page.render(renderContext) }) } // dom结构 <canvas id="pdf-render" ></canvas>