How To Add Page Number In PDF File In React Native

  Jul 2023
  ITSolutionsGuides
  Category: React JS
How To Add Page Number In PDF File In React Native

Hi Developers,

Lets see How To Add Page Number In PDF File In React Native.

Install React and react-pdf

Lets install react-pdf

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 or 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

pageNumber - > Current page number
totalPages Text only - > The total amount of pages in the final document
subPageNumber - > Current subpage in the Page component
subPageTotalPages Text only - > The total amount of pages in the Page component

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);

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides