1.安裝並引入react-pdf
https://github.com/wojtekmaj/react-pdf/blob
npm i react-pdf --save
import { Document, Page, pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
//1.解決報錯
Uncaught SyntaxError: Unexpected token < index.js:1452
Error: Setting up fake worker failed: "Cannot read property 'WorkerMessageHandler' of undefined". at pdf.js:10999
如果任然報錯 替換
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
// 版本問題
2.簡易版---點擊翻頁預覽
<div className={styles.pdfModal}> <div className={styles.pdf_container} onContextMenu={preventDefault} > <Document file={file} className={styles.pdf_document} loading={documentLoading} //自定義加載內容 onLoadSuccess={documentOnLoadSuccess} //加載完成 noData={noData} //空內容顯示 >
<Page
className={styles.pdf_page} pageNumber={pdfIndex} height={ 800 } //固定高度
/>
</Document> </div> <div className={styles.btnContainer}> <Pagination
defaultCurrent={1}
total={numpages}
onChange={changePage}
/> </div>
</div>
//頁面加載完回調 const documentOnLoadSuccess = (pdf: any) => { console.log('加載完', pdf) let numPages = pdf.numPages; setNumPages(numPages) }
//自定義加載loading const documentLoading = () => { return <div>Please wait!</div>; }
//請求獲取pdf的地址 useEffect(() => { api.getpreview(params).then((res) => { if (res && res.byteLength) { setFile(res); } else { setNoData(<div>no pdf</div>) } }); }, []) //阻止右鍵默認事件(禁止下載) const preventDefault = (e: any) => { e.preventDefault() } //點擊翻頁 const [pdfIndex, setPdfIndex] = useState(1) const changPage = (page)=>{
setPdfIndex(page)
}
//獲取pdf地址接口
//返回數據類型
responseType: 'arraybuffer'
responseType: 'blob'
blob轉換成base64:
let reader = new FileReader()
reader.readAsDataUrl(blob)
reader.onload = (e)=>{
resolve(e.target.result)
}
//數據攔截
interceptor(res: any) {
console.log('res', res);
if (res?.headers['content-type']?.includes('pdf')) {
return Promise.resolve(res.data);
}
}