React pdf를 사용하여 React에 온라인/오프라인 pdf 파일 표시

1625 단어 pdfjsreactreactpdf
react pdf는 react의 훌륭한 패키지입니다. pdf를 기반으로 합니다.Mozilla에서 온 js.
  • 설치npm i react-pdf
  • 수입
  • import { Document, Page, pdfjs } from 'react-pdf'
    // right after your imports
    pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`
    
  • 사용
  • <Document
      file={{ url: urlPdf }}
      onLoadSuccess={onDocumentLoadSuccess}
    >
      // pages here, we will get back to that later
    </Document>
    
    위 코드에서 urlPDF는 pdf의 URL입니다.이 자원은 CORS에서 차단할 수 없습니다.그렇지 않으면 pdf를 보여줄 수 없습니다.
    만약 자원을 크로스 소스에 사용할 수 없다면, 그것을 사용하십시오. (단지 임시 해결 방안일 뿐, 생산에서 사용하지 마십시오.)
    file={{ url: `https://cors-anywhere.herokuapp.com/${urlPdf}` }}
    
  • 파일이 로드되면 onLoadSuccess가 호출됩니다. 이 옵션을 사용하여 pdf의 전체 페이지 수를 설정합니다.
    const[totalPages,setTotalPages]=useState(null)
    const onDocumentLoadSuccess=({numPages})=>setTotalPages(numPages)
  • 이제 토탈페이지가 생겼습니다. 페이지를 보여 드리겠습니다.
  • <Document
      file={{ url: attachment.url }}
      onLoadSuccess={onDocumentLoadSuccess}
    >
      {
        Array.apply(null, Array(totalPages))
         .map((x, i) => i + 1)
         .map((page) => <Page pageNumber={page} />)
      }
    </Document>
    
  • 브라우저에서 IDM 확장 모듈을 닫습니다. 그렇지 않으면 파일을 다운로드하라는 메시지가 표시되고 브라우저에서 "로드 실패"오류가 발생합니다.
  • 참고 문헌
    https://github.com/wojtekmaj/react-pdf
  • 좋은 웹페이지 즐겨찾기