Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To add only the heading of the last page to the Table of Contents in PHPWord, you can add a bookmark to the heading on the last page and then add it to the Table of Contents using the addLink method.

Here's an example code snippet:

// Create PHPWord object
$phpWord = new \PhpOffice\PhpWord\PhpWord();

// Add a section
$section = $phpWord->addSection();

// Add some content to the section
$section->addText('Some content');
$section->addPageBreak();

// Add the last page content with a bookmark
$lastPageSection = $phpWord->addSection();
$lastPageSection->addText('Last page content', array('size' => 14, 'bold' => true));
$lastPageSection->addBookmark('last-page');

// Add a Table of Contents
$tocStyle = array('tabLeader' => \PhpOffice\PhpWord\Style\TOC::TAB_LEADER_DOT, 'textAlignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER);
$section->addTOC($tocStyle);

// Add the bookmarked heading to the Table of Contents
$toc = $section->getTOC();
$toc->addLink('Last page heading', 'last-page', null, \PhpOffice\PhpWord\SimpleType\TblWidth::AUTO);

In this example, the addBookmark method is used to add a bookmark named "last-page" to the heading on the last page. Then, the addLink method is used to add the heading to the Table of Contents, with the bookmark name and other optional parameters. Only the last page heading will be added to the Table of Contents, not the entire page.