How can i create a table using the react-pdf library for generation pdf report?

Nayan Dey picture Nayan Dey · May 30, 2019 · Viewed 8.3k times · Source

As the react-pdf library offering some limited component and no html tag is allowed to render in reactpdfrenderer.So i am in a trouble to make table using this library? Can any one please help me how can i create a table using this react-pdf library components?

Answer

Yash picture Yash · Apr 15, 2021

you can use as @David-Kucsai told in comment @david.kucsai/react-pdf-table

or without using

small example

data

const data = {
  id: "5df3180a09ea16dc4b95f910",
  items: [
    {
      sr: 1,
      desc: "desc1",
      xyz: 5
    },
    {
      sr 2,
      desc: "desc2",
      xyz: 6
    }
  ],
};

app.js

import React, { Component, Fragment } from 'react';
import {PDFViewer} from '@react-pdf/renderer'
import Table from './components/reports/Table'
import data from './data'


class App extends Component {
  render() {
    return (
        <Fragment>
            <PDFViewer width="1000" height="600">
                <Table data={data}/>
            </PDFViewer>
        </Fragment>
    );
  }
}

export default App;

Table.js

import React from 'react';
import { Page, Document, StyleSheet } from '@react-pdf/renderer';
import ItemsTable from './ItemsTable'


const styles = StyleSheet.create({
    page: {
        fontSize: 11,
        flexDirection: 'column',
    }
  });
  
  const Table = ({data}) => (
            <Document>
                <Page size="A4" style={styles.page}>
                    // ...
                    <ItemsTable data={data} />
                    // ...
                </Page>
            </Document>
        );
  
  export default Table

ItemsTable.js

import React from 'react';
import {View, StyleSheet } from '@react-pdf/renderer';


const styles = StyleSheet.create({
    tableContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
});

  const ItemsTable = ({data}) => (
    <View style={styles.tableContainer}>
        {/*<TableHeader />*/}
        <TableRow items={data.items} />
        {/*<TableFooter items={data.items} />*/}
    </View>
  );
  
  export default ItemsTable

TableRow.js

import React, {Fragment} from 'react';
import {Text, View, StyleSheet } from '@react-pdf/renderer';


const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    description: {
        width: '60%',
    },
    xyz: {
        width: '40%',
    }
  });


const TableRow = ({items}) => {
    const rows = items.map( item => 
        <View style={styles.row} key={item.sr.toString()}>
            <Text style={styles.description}>{item.desc}</Text>
            <Text style={styles.xyz}>{item.xyz}</Text>
        </View>
    )
    return (<Fragment>{rows}</Fragment> )
};
  
export default TableRow

for more information check Generate Dynamic PDF Invoices Using React and React-PDF