How can FPDF be used to add a table of contents at the beginning of a dynamically generated PDF?

To add a table of contents at the beginning of a dynamically generated PDF using FPDF, you can create a separate class or function that generates the table of contents based on the content of the PDF document. This class or function can iterate through the pages of the PDF, extract headings or titles, and create links to those pages in the table of contents. Once the table of contents is generated, it can be added to the beginning of the PDF document before any other content is added.

```php
// Add a table of contents to a dynamically generated PDF using FPDF

require('fpdf.php');

class PDFWithTOC extends FPDF {
    protected $toc = array();

    function addTOCPage() {
        $this->addPage();
        $this->setLink($this->toc[0]['y']);
        $this->SetFont('Arial','B',16);
        $this->Cell(0,10,'Table of Contents',0,1,'C');
        $this->Ln(10);
        foreach($this->toc as $item) {
            $this->Cell(0,10,$item['title'],0,1,'L',false,$item['link']);
        }
    }

    function addTOCEntry($title) {
        $this->toc[] = array('title' => $title, 'y' => $this->GetY());
    }
}

$pdf = new PDFWithTOC();

$pdf->addTOCEntry('Chapter 1: Introduction');
$pdf->addTOCEntry('Chapter 2: Methods');
$pdf->addTOCEntry('Chapter 3: Results');
$pdf->addTOCEntry('Chapter 4: Conclusion');

$pdf->addTOCPage();

$pdf->SetFont('Arial','',12);
$pdf->addPage();
$pdf->Cell(0,10,'Chapter 1: Introduction',0,1);
$pdf->Cell(0,10,'This is the introduction chapter.',0,1);

$pdf->addPage();
$pdf->Cell(0,10,'Chapter 2: Methods',0,1);
$pdf->Cell(0,10,'This is the methods chapter.',0,1);

$pdf->addPage();
$pdf->Cell(0,10,'Chapter 3: Results',0,1);
$pdf->Cell(0,10,'This is the results chapter.',0,1);

$pdf->addPage();
$pdf->Cell(0,10,'Chapter 4: