Search code examples
phpphpwordphpoffice

Adding style to all link tags in PHPWord


I'm using PHPWord in order to parse HTML content and generate a .docx file from it. I want to add style to all tags so they'll look like HTML links in a web page, e.g: blue with underline. right now they was they look in the generate .docx file is black with no underline text.

this is the code right now:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();

$content = 'one two <a href="https://google.com/">three</a> four five';

\PhpOffice\PhpWord\Shared\Html::addHtml($section, $content, false, false);

$phpWord->save('myfile.docx', 'Word2007', true);

I am aware I could use inline CSS (and it works) like this:

$content = 'one two <a href="https://google.com/" style="color: blue; text-decoration: underline;">three</a> four five';

But I really don't want to do so to every tag. I want to be able to set styling like it's possible in a paragraph or heading like "addTitleStyle" for any incoming tags.

also, I cannot use "addLink", I currently must be using "addHtml"


Solution

  • After addHtml you can do this:

    /** @var \PhpOffice\PhpWord\Element\Section $section */
    foreach($phpWord->getSections() as $section)
    {
      foreach($section->getElements() as $element)
      {
        if($element instanceof \PhpOffice\PhpWord\Element\Link)
        {
          $fontStyle = $element->getFontStyle();
          $fontStyle->setColor('#0000ff')
          ->setUnderline('single');
        }
      }
    }