pc端pdf预览

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
相关推荐
10年前端老司机21 分钟前
Next.js+LangGraph.js+ 简历工具AI Agent完整落地
前端·langchain·agent
IT_陈寒5 小时前
Java中equals方法比了个寂寞?原来这才是正确的重写姿势
前端·人工智能·后端
默_笙5 小时前
🚓 分诊台与拆题术:让 RAG 学会判断和规划
前端·javascript
CopyCode5 小时前
用 AI 迁项目有多爽?我把 Webpack 迁 Vite 的全过程记下来了
前端·架构
去伪存真5 小时前
Electron 自动化发布指南:GitHub Actions 跨平台打包全纪录
前端·electron
计算机魔术师5 小时前
OpenAI智能体失控闯进美国政府网站,53张用户图片外泄背后
前端
颜进强5 小时前
14 · NestJS ExecutionContext 执行上下文:守卫、拦截器、过滤器拿到的"同一个 context",为什么能力不一样?
前端·后端·ai编程
程序员Flycan5 小时前
🚀 跨域终结者:前端代理服务器(Proxy)原理解析与配置总结
前端
怕浪猫5 小时前
顶级模型一句话,AI 写出了能玩的 QQ飞车
前端·面试·github
huakoh5 小时前
MCP 报错分不清?先看响应里是 result 还是 error
前端