0

Please i am try to generate a pdf document since some weeks and have finsh but something missing in the table. i want to give the ability to user to see table of content with his page number. can Somebody help me. Thanks

RuthelCrab
  • 153
  • 10

2 Answers2

2

To the people arriving to this question. I managed to get it done with the following code.

config are style settings. blocks are the different chapters the PDF should have. The important part is the function recalculateIndex, executed when the render callback executes getPageNumber on every <Text /> in order to get the page number. If I'm not wrong, React PDF run this render twice, the first one it get the total pages, and in the second it assign the number of every page. By setting the index state it just triggers a new render with the new index ready to be printed. The condition only ensure the update to only take place at the end of the second Text render and only if the index actually changed.

const Template = ({ config, blocks }) => {
  const [index, setIndex] = useState([])
  const newIndex = []
  const equals = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);

  const recalculateIndex = (i, pageNumber, totalPages) => {
    newIndex[i] = newIndex[i] ? newIndex[i] : pageNumber
    if (pageNumber === totalPages && !equals(index, newIndex)) {
      // SET NEW INDEX
      setIndex(newIndex)
    }
  }

  const getPageNumber = (i, pageNumber, totalPages) => {
    recalculateIndex(i, pageNumber, totalPages)
    return (`${pageNumber} / ${totalPages}`)
  }
  return (
    <Document>

      <Page size={config.global.format} style={styles.page}>
          {index && index.map((ch, i) => (<Text key={i}>{ch}</Text>))}
      </Page>

      {blocks.map((block, i) =>
        <Page key={i} size={config.global.format} style={styles.page}>
          <Content content={block} config={config} />
          <Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => getPageNumber(i, pageNumber, totalPages)} fixed />
        </Page>
      )}
    </Document>
  )
}

You can extend it to store titles and so on.

Thanks to RuthelCrab to clear my doubts and point me to the right direction.

diegozen
  • 21
  • 4
0

oh i've found. the answer was juste to stop the ability of the component to update, store the different page of table of content in and array with the title. save this table of content, unmount the pdf draft, and mount the new table of content in the final pdf

RuthelCrab
  • 153
  • 10