柚子青年。

柚子青年。

任何人浪费时间在这件事上都能这样

React - PDF 预览

发布时间:2020-07-04 22:07

本文主要是介绍如何实现一个 PDF 预览功能

react-pdf

一个用来展示 pdf 的react插件 [传送门]

简单封装
  1. import React, {useState} from "react";
  2. import styled from "styled-components";
  3. import {Document, Page, pdfjs} from "react-pdf";
  4. pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
  5. const App = styled(({className}) => {
  6. const [pageNo, setPageNo] = useState(1);
  7. const [pageSize, setPageSize] = useState(null);
  8. const onDocumentLoadSuccess = ({numPages}) => {
  9. setPageSize(numPages);
  10. };
  11. const prevPage = () => {
  12. if (pageNo > 1) setPageNo(pageNo - 1);
  13. };
  14. const nextPage = () => {
  15. if (pageNo < pageSize) setPageNo(pageNo + 1);
  16. };
  17. return (
  18. <div className={className}>
  19. <Document
  20. file="/pdf/github-git-cheat-sheet.pdf"
  21. onLoadSuccess={onDocumentLoadSuccess}
  22. >
  23. <Page width={600} pageNumber={pageNo}/>
  24. <p className="pagination">
  25. <span className={pageNo === 1 && "disable"} onClick={prevPage}>&lt;</span>
  26. {pageNo} / {pageSize}
  27. <span className={pageNo === pageSize && "disable"} onClick={nextPage}>&gt;</span>
  28. </p>
  29. </Document>
  30. </div>
  31. );
  32. })`
  33. position: relative;
  34. width: 600px;
  35. height: 800px;
  36. margin: 0 auto;
  37. background: #fff;
  38. overflow: auto;
  39. .pagination{
  40. position: absolute;
  41. left: 0;
  42. bottom: 0;
  43. width: 100%;
  44. font-size: 12px;
  45. line-height: 24px;
  46. text-align: center;
  47. background: #fff;
  48. margin: 0;
  49. span{
  50. margin: 0 10px;
  51. cursor: pointer;
  52. &.disable{
  53. color: #999;
  54. cursor: no-drop;
  55. }
  56. }
  57. }
  58. `;
  59. export default App;