How to generate TOC from HTML in phpword

Viewed 617

I am using PHPWord library to convert my HTML document to Docx file.

I have issue in generating TOC(Table of contents) correctly in Word document. In HTML, TOC is created by # linking of anchor tags with divs and working perfectly. How can i convert it to Docx TOC using PHPWord?

My code to generate HTML to Docx is as follows:

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();        
        \PhpOffice\PhpWord\Shared\Html::addHtml($section,$htmlContent);
        $targetFile = __DIR__ . "/convertedFile.docx";
        $phpWord->save($targetFile, 'Word2007');

Library link: PHPWord

1 Answers
 <form method="post" action="gendocx.php">
 <input type="hidden" name="htmlstring" id="htmlstring" value="">
 <input type="submit" id="MyButton" value="Generate Docx">
 </form>
 ...
 <script>
 $('#myButton').click(function(){
 //get your Div HTML trying
 var s = $('#myHTMLDiv').html();
 $('#htmlstring').val(s);
 });
 </script>


Then in gendocx.php we’ll take the incoming HTML string and put it into Docx document 
like this.

require_once 'vendor/autoload.php';

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $_POST['htmlstring']);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename="test.docx"');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('php://output');
Related