PHPWord如何在文本运行中添加文本中断/换行

use*_*723 6 php format line phpword

如何在文本运行中添加文本中断或转到下一行/行?我试着$section->addTextBreak(2);在文本运行中做,但它只是在文本运行后将断点添加到该部分.我也试过,$textrun->addTextBreak(2);但它给了我一个致命的错误.任何回复将不胜感激.

小智 11

问题在3年前被问到,但我遇到了同样的问题,我找到了解决方案.也许这可以帮助PHPWord的新用户.

要在Word文档中添加crlf,标记可以提供帮助:

$section->addText('Some text <w:br/> another text in the line ');
Run Code Online (Sandbox Code Playgroud)

我在这里找到了解决方案:http://jeroen.is/phpword-line-breaks/


小智 8

试试这个:

    str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $yourData );
Run Code Online (Sandbox Code Playgroud)

或者这个

    str_replace("\r\n", '</w:t><w:br/><w:t xml:space="preserve">', $yourData );
Run Code Online (Sandbox Code Playgroud)


j0h*_*hny 6

我担心目前的版本无法做到这一点.我对这个库没有深刻的理解,但是通过查看代码,我发现textRun该类只包含addTextaddLink方法.

但是我也需要这个功能以及其他几个,所以我将自己编写并创建一个pull请求,以便将它包含在下一个版本中(如果有的话).

基本上它可以通过修改textRun类,添加一个addLineBreak方法(类似于在section类中)然后修改类Base.php来在最终文档中创建适当的元素来完成.

在Docx xml中,这些行制动器类似于html br标签,但是在使用break之后必须关闭并重新打开以前的文本:

<w:r>
  <w:t>This is</w:t>
  <w:br/>
  <w:t xml:space="preserve"> a simple sentence.</w:t>
</w:r>
Run Code Online (Sandbox Code Playgroud)

而不是简单地做

<w:r>
  <w:t>This is<w:br /> a simple sentence</w:t>
</w:r>
Run Code Online (Sandbox Code Playgroud)

因此base.php,您需要编辑行为以创建此代码块.

希望这很有用!

编辑

我已经发现实现这一点非常简单.在textRun.php刚刚加入这个方法:

/**
* Add a TextBreak Element
*
* @param int $count
*/
public function addTextBreak($count = 1) {
    for($i=1; $i<=$count; $i++) {
        $this->_elementCollection[] = new PHPWord_Section_TextBreak();
    }
}
Run Code Online (Sandbox Code Playgroud)

并且Base.php_writeTextRun此方法结束方法添加此条件:

elseif($element instanceof PHPWord_Section_TextBreak) {
    $objWriter->writeElement('w:br');
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*uni 6

您可以有一个文本并\n在您想要换行的位置添加,然后像这样执行其余操作:

$text = "foo\nbar\nfoobar";
$textlines = explode("\n", $text);

$textrun = $section->addTextRun();
$textrun->addText(array_shift($textlines));

foreach($textlines as $line) {
    $textrun->addTextBreak();
    // maybe twice if you want to seperate the text
    // $textrun->addTextBreak(2);
    $textrun->addText($line);
}
Run Code Online (Sandbox Code Playgroud)