最近項(xiàng)目上有預(yù)覽PDF文檔的需求,原本使用object實(shí)現(xiàn)這個(gè)功能,代碼如下:
<object data={this.state.pdfContent}
type="application/pdf"
width="100%"
height="1200px"
standby="pdf文檔加載中..."
>
This browser does not support PDFs.
</object>
其效果圖如下:

object.gif
但是此時(shí)頁(yè)面出現(xiàn)了兩個(gè)滾動(dòng)條,不是我們想要的效果,而且也存在瀏覽器兼容問(wèn)題,因此,換用react-pdf 實(shí)現(xiàn)這一功能。先上一個(gè)修改好的效果圖:

pdf示例.gif
使用react-pdf時(shí),首先要安裝插件:
npm i react-pdf
然后在組件中引用:
import { Document, Page } from 'react-pdf';
最后在組件render函數(shù)中引入
<Document
file={this.state.pdfContent}//文檔地址
loading=""
onLoadSuccess={this.onDocumentLoadSuccess}
>
<Page
key={this.state.currentPage}
pageNumber={this.state.currentPage} //當(dāng)前頁(yè)頁(yè)碼
width={850}
/>
</Document>
其中onLoadSuccess為加載完的回調(diào)函數(shù)
onDocumentLoadSuccess = ({ numPages }) => {//numPages是總頁(yè)數(shù)
this.setState({ numPages });
};
注意:效果圖上的分頁(yè)是結(jié)合antd的Pagination來(lái)實(shí)現(xiàn)的。
react-pdf的具體文檔鏈接:https://www.npmjs.com/package/react-pdf