向PHPWord中的所有链接标签添加样式

问题描述

我正在使用PHPWord来解析HTML内容并从中生成一个.docx文件。 我想为所有标签添加样式,以便它们看起来像网页中的HTML链接,例如带下划线的蓝色。 现在他们看到的是在生成的.docx文件中看到的是黑色,没有下划线文本。

这是现在的代码

$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);

我知道我可以像这样使用内联CSS(并且可以工作):

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

但是我真的不想对每个标签都这样做。 我希望能够在任何传入标签中的段落或标题“ addTitleStyle”之类的样式中进行设置。

另外,我不能使用“ addLink”,我当前必须使用“ addHtml”

解决方法

addHtml之后,您可以执行以下操作:

/** @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');
    }
  }
}