在PHPWord中使用setValue将word加粗

rdrgkggo  于 2023-08-02  发布在  PHP
关注(0)|答案(2)|浏览(220)

如何在PHPWord中使用TemplateProcessor时使替换的单词粗体和下划线?找到的解决方案非常古老(2016)。
我试图创建我的功能,编辑XML文档,但完成文件崩溃.
我的代码:

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

$document = new TemplateProcessor($path);

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

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

字符串
尝试此功能:

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

qmelpv7a

qmelpv7a1#

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

字符串

cyej8jka

cyej8jka2#

我试着编写我自己的代码,所以它可以处理是否有一个以上的<strong>标签或有<em>标签太在一个句子中。这个想法是我做我自己独特的标签来取代HTML标签。

$yourInputString = "The last word of this sentence is <strong>bold</strong>";

$yourInputString = str_replace("<strong>","|@@|CUSTOMID=01", $yourInputString);
$yourInputString = str_replace("</strong>","|@@|", $yourInputString);

$yourInputString = str_replace("<em>","|@@|CUSTOMID=02", $yourInputString);
$yourInputString = str_replace("</em>","|@@|", $yourInputString);

// $yourInputString = "The last word of this sentence is |@@|CUSTOMID=01bold|@@|"

$exploded = explode("|@@|", $yourInputString);

/* $exploded = [
    'The last word of this sentence is',
    'CUSTOMID=01bold',
    '',
]
*/

$sentence = new TextRun();

for ($j=0; $j < count($exploded); $j++) {
    // I take 11 first character and check whether it's bold or italic
    if (substr($exploded[$j],0,11) == 'CUSTOMID=01') {
        //BOLD TEXT
        $sentence->addText(substr($exploded[$j],11), array('name' => 'Tahoma', 'size' => '11', 'bold' => true));
    }elseif (substr($exploded[$j],0,11) == 'CUSTOMID=02') {
        //ITALIC TEXT
        $sentence->addText(substr($exploded[$j],11), array('name' => 'Tahoma', 'size' => '11', 'italic' => true));
    }else{
        //DEFAULT TEXT
        $sentence->addText(substr($exploded[$j],0), array('name' => 'Tahoma', 'size' => '11'));
    }
}

$templateProcessor->setComplexValue('some_placeholder', $sentence);

字符串

相关问题