首页 > 解决方案 > 为 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”

标签: phpphpwordphpoffice

解决方案


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

推荐阅读