How To Add Page Number In PDF File In React JS

In this article, we will see how to add page numbers in a pdf file in react js. Here we will learn how to add dynamic content in a pdf file in react js application. Sometimes we need to add dynamic content to the pdf file like generating invoices, documents, reports, etc.

So, let's see react-pdf page numbers, how to add pagination in pdf file react js, how to add dynamic content in pdf in react js, and react js create a pdf file.

We are using the react-pdf package to generate PDF files. React-pdf creating PDF files on the browser and server. 

Install React and react-pdf

Starting with react-pdf is extremely simple.

Using yarn

yarn add @react-pdf/renderer

Using npm

npm install @react-pdf/renderer --save

 

Add Dynamic Page Number 

With react-pdf, now it is possible to render dynamic text based on the context. we need to pass a function to the render prop of the <Text /> or <View /> component.

import { Document, Page } from '@react-pdf/renderer'

const doc = () => (
  <Document>
    <Page wrap>
      <Text render={({ pageNumber, totalPages }) => (
        `${pageNumber} / ${totalPages}`
      )} fixed />

      <View render={({ pageNumber }) => (
        pageNumber % 2 === 0 && (
          <View style={{ background: 'red' }}>
            <Text>I'm only visible in odd pages!</Text>
          </View>
        )
      )} />
    </Page>
  </Document>
);

 

Page Number arguments

react-pdf provides the below argument for page number display in pdf file. 

Name Description Type
pageNumber Current page number Integer
totalPages Text only The total amount of pages in the final document Integer
subPageNumber Current subpage in the Page component Integer
subPageTotalPages Text only The total amount of pages in the Page component Integer

 

Example:

const styles = StyleSheet.create({
  page: { padding: 60 },
  box: { width: '100%', marginBottom: 30, borderRadius: 5 },
  pageNumbers: {
    position: 'absolute',
    bottom: 20,
    left: 0,
    right: 0,
    textAlign: 'center'
  },
});

const doc = (
  <Document>
    <Page style={styles.page} size="A4" wrap>
      <View style={[styles.box, { height: 400, backgroundColor: 'black' }]} />
      <View style={[styles.box, { height: 280, backgroundColor: 'lightgray' }]} />
      <View style={[styles.box, { height: 600, backgroundColor: 'deepskyblue' }]} />
      <View style={[styles.box, { height: 400, backgroundColor: 'olive' }]} />
      <Text style={styles.pageNumbers} render={({ pageNumber, totalPages }) => (
        `${pageNumber} / ${totalPages}`
      )} fixed />
    </Page>
  </Document>
);

ReactPDF.render(doc);

Output:

page_number_react_js

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS