Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load more than 1 pdf pages in 'react-pdf'

I am building a project in React that has a functionality of displaying pdfs. I am using the basic minimal code provided in the example (in the repo) itself. However, the code displays only the first page of the pdf and the rest are ignored. am using 'react-pdf' for this. I

Following is my code ..

import React, {Component} from 'react';
import './DocumentationPage.css';
import HeaderComponent from '../../components/Header/Header.js';
import { Document, Page } from 'react-pdf/build/entry.webpack';
import data from './data.pdf';
// import { Document, Page } from 'react-pdf';

export default class DocumentationPage extends Component {
    state = {
        numPages: 12,
        pageNumber: 1,
      }

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

        return (
            <div>
                <HeaderComponent id='header' location={this.props.location} />
                <div>
                    <h1>Documentation</h1>
                </div>
                <div id='contentDiv'>
                    <Document
                        file={data}
                        onLoadSuccess={this.onDocumentLoad}>
                            <Page pageNumber={pageNumber} />
                    </Document>
                    <p>Page {pageNumber} of {numPages}</p>
                </div>
            </div>
        );
    }
}

Please help. Thank You.

like image 245
iamrkcheers Avatar asked Nov 10 '17 14:11

iamrkcheers


2 Answers

A more generic way to render all pages if total number of pages is not known...

const [numPages, setNumPages] = useState(null);
.
.
.
<Document
    file={data}
    onLoadSuccess={({ numPages })=>setNumPages(numPages)}
>
    {Array.apply(null, Array(numPages))
    .map((x, i)=>i+1)
    .map(page => <Page pageNumber={page}/>)}
</Document>
like image 107
ritesrnjn Avatar answered Nov 06 '22 21:11

ritesrnjn


Due to this project still in development, not very clear document to show how to show all pages, but there's a pageNumber attribute inside <Page /> for you to control the page that showing on PDF.

So if you know the total page num, you can just add more <Page /> component for displaying all page in pdf by looping of just copy and past

e.g.

<Document
    file={data}
    onLoadSuccess={this.onDocumentLoad}>

        // Showing page 1,2,3,10,11,12
        {[1,2,3,10,11,12].map(page => (
            <Page pageNumber={page} />
        ))}

</Document>
like image 9
Stanley Cheung Avatar answered Nov 06 '22 22:11

Stanley Cheung