react语法
javascript
import React, { useState } from 'react'
import { Modal, Spin, Alert } from 'antd'
import { Document, Page, pdfjs } from 'react-pdf'
import 'react-pdf/dist/esm/Page/AnnotationLayer.css'
import 'react-pdf/dist/esm/Page/TextLayer.css';
// 配置 PDF.js 的 worker 文件
pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.js', import.meta.url).toString()
interface PDFPreviewModalProps {
fileName: string | null
fileUrl: string | null // 传入的 PDF 文件地址
onCancel: () => void // 关闭弹框的回调
}
const PDFPreviewModal: React.FC<PDFPreviewModalProps> = ({ fileName, fileUrl, onCancel }) => {
const [numPages, setNumPages] = useState<number | null>(null)
const [pdfWidth, setPdfWidth] = useState<number>(600) // 默认宽度为 600px
const [loading, setLoading] = useState<boolean>(true) // 控制加载状态
const [error, setError] = useState<boolean>(false) // 控制加载错误状态
// 当 PDF 加载成功时,设置页面数量
const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
setNumPages(numPages)
setLoading(false) // 加载成功后,隐藏 loading
}
// 加载失败时,设置错误状态
const onDocumentLoadError = () => {
setLoading(false)
setError(true) // 出错时显示错误提示
}
// 获取 PDF 页面加载后的宽度
const onPageLoadSuccess = ({ width }: { width: number }) => {
setPdfWidth(width)
}
return (
<Modal
title={`【${fileName}】预览`}
open
onCancel={onCancel}
footer={null}
width={pdfWidth + 100}
style={{ top: 20 }}
>
{error ? (
<Alert message="加载 PDF 文件失败" type="error" showIcon />
) : (
<>
{loading && (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }}>
<Spin size="large" />
</div>
)}
{fileUrl && (
<>
<div style={{ height: '88vh', overflowY: 'auto', padding: '24px' }}>
<Document
//file={new URL('/public/temp/DXF文件要求.pdf',import.meta.url).toString()}
file={fileUrl}
onLoadSuccess={onDocumentLoadSuccess}
onLoadError={onDocumentLoadError}
>
{Array.from(new Array(numPages), (el, index) => (
<Page key={`page_${index + 1}`} pageNumber={index + 1} onLoadSuccess={onPageLoadSuccess} />
))}
</Document>
</div>
</>
)}
</>
)}
</Modal>
)
}
export default PDFPreviewModal