Skip to content

Make word bold with setValue in PHPWord

How to make the replaced word bold and underline when using TemplateProcessor in PHPWord? Found solutions are very old (2016).

I tried to create my function, to edit xml document, but done file is crashing.

My code:

$path = public_path()."/example/dogovor.docx";

$document = new TemplateProcessor($path);

$document->setValue('student-name', 'Alex');

$document->saveAs(public_path("documents/test.docx"));

Tried this function:

private function makeWordBold($str, $hex=null, $style='b'): string
    {
        $cor = $hex ? "<w:color w:val='".$hex."'/>" : "";
        $before="/w:t/w:r<w:r><w:rPr>".$cor."<w:".$style."/>/w:rPr<w:t xml:space='preserve'>";
        $after='/w:t/w:r<w:r><w:t>';
        return $before.$str.$after;
    }

Advertisement

Answer

$path = public_path()."/example/dogovor.docx";

$document = new TemplateProcessor($path);
$word = new TextRun();
$word->addText('Alex', array('underline' => 'single', 'bold' => true));
$document->setComplexValue('student-name', $word);
$document->saveAs(public_path("documents/test.docx"));
User contributions licensed under: CC BY-SA
9 People found this is helpful