react display a pdf file screen displays all pages

background

Received a demand, we need a page to showcase multiple PDF files and need to scroll simultaneously.

Initially thought of using iframe rendering PDf, but given the poor control of the iframe rendering a PDF file, and then began to find two PDF rendering library online

react-pdf-js click to enter the official documentation
react-pdf Click to enter official documents

After comparing the two libraries found greater react-pdf amount of users, documents clearer, more comprehensive functions, so use the react-pdf.

installation

Note: To go to download before using according react their own version of the project react-pdf version corresponding to install the latest version of the react-pdf by npm default, React version requires ≥16.3, need to find the corresponding version, click into the react-pdf official website to view it

  • Installation react-pdf package
npm install react-pdf --save
  • The introduction and use of components
import React, { Component } from 'react';
import { Document, Page } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css' // 加入这个css可以显示pdf中的批注以及连接

class MyApp extends Component {
  state = {
    numPages: null,
    pageNumber: 1,
  }

  onDocumentLoadSuccess = ({ numPages }) => {
    this.setState({ numPages });
  }

  render() {
    const { pageNumber, numPages } = this.state;

    return (
      <div>
        <Document
          file="一个PDF的连接.pdf"
          onLoadSuccess={this.onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
        <p>Page {pageNumber} of {numPages}</p>
      </div>
    );
  }
}

Display method

Next page

Want to control page, then just like a dynamic change pageNumber

A display screen

The total number of pages can be obtained according to onLoadSuccess, then loop Page generated component based on the total number of pages, you can display a screen all the pages

render() {
    const { pageNumber, numPages } = this.state;

    return (
        <div>
            <Document file="一个PDF的连接.pdf"  onLoadSuccess={this.onDocumentLoadSuccess }>
                    {
                        new Array(numPages).fill('').map((item, index) => {
                            return <Page key={index} pageNumber={index} />
                        })
                    }
            </Document>
         </div>
    );
}
Epilogue

There are many react-pdf api, tips, pdf file zoom ratio displayed when loading and loading failures such as for example, so if you need to meet more needs to remember to see the document!

Guess you like

Origin www.cnblogs.com/slongs/p/12512359.html