How to add hyperlink using templateprocessor (PHPWord Library)

1k Views Asked by At

I want to replace email variable into a hyperlink using template processor and I have used two way to solved this issue but didn't work and here is our below code for replacing email variable into hyperlink but when I used setValue or setComplexValue function for replacement value then document is corrupted.

We have tried below two scenarios for adding hyperlink but didn't work for us.

1. First Way

$pw = new \PhpOffice\PhpWord\PhpWord();
$section = $pw->addSection();
$textrun = $section->addTextRun();
$textrun->addTextBreak(2);
$section->addLink('mailto:[email protected]?subject=DEMO','[email protected]', array('color' => 'FF0000', 'underline' =>
\PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($pw, 'Word2007');
$fullXml = $objWriter->getWriterPart('Document')->write();
$templateProcessor->setValue($var, $this->getBodyBlock($fullXml));

2. Second Way

$pw = new \PhpOffice\PhpWord\PhpWord();
$section = $pw->addSection();
$convertResult = '[email protected]';

\PhpOffice\PhpWord\Shared\Html::addHtml($section, $convertResult, false,false);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($pw, 'Word2007');
$fullXml = $objWriter->getWriterPart('Document')->write();
$templateProcessor->setValue($var, $this->getBodyBlock($fullXml)); 

protected function getBodyBlock($string) {
   if (preg_match('%(?i)(?<=<w:body>)[\s|\S]*?(?=</w:body>)%', $string, $regs)) {
       return $regs[0];
    } else {
       return '';
    }
}

Please help us thank in advance.

0

There are 0 best solutions below