用create-react-app建立一個新的react項目react
npx create-react-app my-app
npm install pdfjs-dist --save
pdfjs-dist/webpack是已經對pdfjs打包過的文件,不使用可能出現的問題webpack
import pdfjsLib from 'pdfjs-dist/webpack';
對PDF的獲取處理等所有都是異步操做git
const pdf = await pdfjsLib.getDocument('http://xxx/xxx.pdf')
在回調中獲取PDF每頁的對象,並將其內容渲染到canvas中github
for (let _page = 1; _page <= pdf._pdfInfo.numPages; _page++) { pdf.getPage(_page).then((page) => { // page.getViewport 設置縮放倍率 const viewport = page.getViewport({scale: 1}) const canvas = document.createElement('canvas') const context = canvas.getContext('2d') canvas.height = viewport.height canvas.width = viewport.width const renderContext = { canvasContext: context, viewport: viewport, enableWebGL: true, } // page.render將內容渲染到canvas中, // page.render也會返回一個對象,對象有更詳細渲染信息,其中包括渲染好的canvas對象,但這個canvas並非上文聲明的,不可控 // const _canvas = page.render(renderContext) page.render(renderContext) this.pageRenderRef.current.appendChild(canvas) }); }
import React, {Component} from "react"; import pdfjsLib from 'pdfjs-dist/webpack'; export default class PDFViewer extends Component { constructor(props) { super(props) this.pageRenders = [] // 存放每頁pdf造成的canvas this.pageRenderRef = React.createRef() /渲染pdf的容器 } componentDidMount() { this.init() } init = async () => { console.time('pdf加載時間') const pdf = await pdfjsLib.getDocument('http://xxx/xxx.pdf') console.timeEnd('pdf加載時間') const {_pdfInfo: {numPages}} = pdf for (let _page = 1; _page <= numPages; _page++) { pdf.getPage(_page).then((page) => { const viewport = page.getViewport({scale: 1}) const canvas = document.createElement('canvas') const context = canvas.getContext('2d') canvas.height = viewport.height canvas.width = viewport.width const renderContext = { canvasContext: context, viewport: viewport, enableWebGL: true, } page.render(renderContext) this.pageRenderRef.current.appendChild(canvas) }); } } render() { return ( <div ref={this.pageRenderRef}> { this.pageRenders.length > 0 && this.pageRenders } </div> ) } }