diegomura / react-pdf

📄 Create PDF files using React
https://react-pdf.org
MIT License
14.22k stars 1.11k forks source link

is it possible to present a table example? #2719

Open jackzhp opened 1 month ago

jackzhp commented 1 month ago

In the document, is it possible to include an example which present a table. For instance, with 3 rows and 3 columns, while cells with different size, and they are all well aligned, first column and 3-rd column aligned to the right, while the 2nd column aligned to the left.

pietroanello commented 4 weeks ago

You can start from this example and customize everything you want. The simple idea is to recreate a table with the React Pdf components.

const headers = ['header 1', 'header 2', 'header 3']
const data = [[1,2,'test'], [1,2,'a really really long text test'], [1,2,123123123]]

const Quixote = () => {

  const renderHeader = () => {
    return headers.map((header, index) => {
      return (
        <View key={`header_${index}`} style={[styles.headerCell]}>
          <Text style={{ textTransform: 'uppercase' }}>
            {header}
          </Text>
        </View>
      )
    })
  }

  const renderCells = (values, rowIndex) => {
    return values.map((value, index) => {
      return (
        <View key={`cell_${rowIndex}_${index}`} style={[styles.tableCell]}>
          <Text>
            {value}
          </Text>
        </View>
      )
    })
  }

  const renderRows = () => {
    return data.map((row, index) => {
      return (
        <View key={`row_${index}`} style={[styles.row]} wrap={false}>
          {renderCells(row, index)}
        </View>
      )
    })
  }

  return <Document>
    <Page>
      <View style={[{ backgroundColor: 'white', padding: 16, paddingTop: 0 }]}>
        <View fixed style={styles.header}>
          {renderHeader()}
        </View>
        {renderRows()}
      </View>
    </Page>
  </Document>
};

Font.register({
  family: 'Oswald',
  src: 'https://fonts.gstatic.com/s/oswald/v13/Y_TKV6o8WovbUd3m_X9aAA.ttf'
});

const styles = StyleSheet.create({
  header: {
    flexDirection: 'row',
    textAlign: 'left',
    backgroundColor: 'white',
    borderBottom: '0.5px solid black',
    paddingBottom: 16,
    marginBottom: 10,
  },

  headerCell: {
    flex: 1,
  },

  tableCell: {
    flex: 1,
    padding: 2.5,
    paddingHorizontal: 0,
    // textOverflow: 'ellipsis',
    // maxLines: 1,
  },

  row: {
    flexDirection: 'row',
    textAlign: 'left',
    backgroundColor: 'white',
    marginVertical: 2.5,
  },
})

ReactPDF.render(<Quixote />);
kishaningithub commented 1 day ago

Kindly check the discussions in this related issue https://github.com/diegomura/react-pdf/issues/487