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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17689188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:15:43  来源:igfitidea点击:

PHPWord how to add text break / new line while in a text run

phpformatlinephpword

提问by user2579723

How can I add a text break or go to the next line/row while in a text run? I tried to just do $section->addTextBreak(2);while in the text run but it just added the breaks to the section after the text run. I also tried $textrun->addTextBreak(2);but it gave me a fatal error. Any responses would be greatly appreciated.

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

采纳答案by j0hny

I'm afraid that this will not be possible with current version. I don't have deep understanding of this library, but from looking at the code, I found out that the textRunclass consist only of addTextand addLinkmethods.

恐怕这在当前版本中是不可能的。我对这个库没有深入了解,但是通过查看代码,我发现textRun该类仅由addTextaddLink方法组成。

But I also need this feature along with several others, so I'm going to write it myself and create a pull request to get it included in the next release (if there will be any).

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

Basically it can be done by modifying the textRunclass, adding an addLineBreakmethod (similar way as it is in the section class) and then modify class Base.phpto create proper elements in final document.

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

In Docx xml, those line brakes are similar to the html brtag, but previous text must be closed and reopened after using break like this:

在 Docx xml 中,那些 line 刹车类似于 htmlbr标签,但是在使用 break 后必须关闭并重新打开以前的文本,如下所示:

<w:r>
  <w:t>This is</w:t>
  <w:br/>
  <w:t xml:space="preserve"> a simple sentence.</w:t>
</w:r>

instead of simply doing

而不是简单地做

<w:r>
  <w:t>This is<w:br /> a simple sentence</w:t>
</w:r>

So in base.php, you'll need to edit behavior to create this block of code.

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

Hope this was useful!

希望这是有用的!

EDIT

编辑

I have figured out that implementing this is very simple. In textRun.phpjust add this method:

我发现实现这一点非常简单。在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();
    }
}

and in Base.phpin the _writeTextRunmethod at the end of this method add this condition:

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

elseif($element instanceof PHPWord_Section_TextBreak) {
    $objWriter->writeElement('w:br');
}

回答by gaelle3182

The question was asked 3 years ago but I have the same problem and I found a solution. Maybe this can help new users of PHPWord.

这个问题是 3 年前提出的,但我遇到了同样的问题,我找到了解决方案。也许这可以帮助 PHPWord 的新用户。

To add a crlf in Word document the tag can help :

要在 Word 文档中添加 crlf 标签可以帮助:

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

I found the solution here : http://jeroen.is/phpword-line-breaks/

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

回答by Notoc

Adding a newline in phpword has bothered me, and I finnaly found solution, by accident, so here it is: And this justifies the text.

在 phpword 中添加换行符让我感到困扰,我最终偶然找到了解决方案,所以这里是: 这证明了文本的合理性。

$PHPWord->addParagraphStyle('pJustify', array('align' => 'both', 'spaceBefore' => 0, 'spaceAfter' => 0, 'spacing' => 0));
//add this style then append it to text below
$section->addText('something', 'textstyle', 'pJustify');
//the text behind this will be justified and will be in a new line, not in a new paragraph
$section->addText('behind', 'textstyle', 'pJustify');

This will output:

这将输出:

something

某物

behind

在后面

回答by vorvor

It's easy: just start a new textrun, and before it add textbreak to the section, like this (tested with docx format):

这很简单:只需启动一个新的 textrun,然后在将 textbreak 添加到该部分之前,就像这样(使用 docx 格式测试):

$textrun = $section->addTextRun();

$textrun->addText('blah-blah', 'p_bold');

  $section->addTextBreak(2);

  $textrun = $section->addTextRun();

  $textrun->addText('blah-blah-blah in new line ', 'p');

  $textrun->addText('blah-blah', 'p_bold');

  $textrun->addText('blah-blah', 'p');

  $section->addTextBreak(2);

  $textrun = $section->addTextRun();

  $textrun->addText('blahblah', 'p');

回答by Jake

I don't know if a PR from the accepted answer was incorporated or it was in fact already possible in 2013, but regardless, since 2015 if not earlier, the correct way to insert line breaks within a paragraph is indicated in the initial response to #553 on GitHub:

我不知道已接受答案中的 PR 是否已被纳入,或者实际上在 2013 年就已经可能了,但无论如何,自 2015 年以来,如果不是更早,在段落中插入换行符的正确方法在对#553 在 GitHub 上

  • Create a TextRunfor the paragraph;
  • Add line breaks to the TextRunby calling the addTextBreak()method of the TextRunitself.
  • TextRun为段落创建一个;
  • 添加换行符到 TextRun通过调用addTextBreak()方法的的TextRun本身

Here's a function that will take care of this for a complete paragraph of text in a string containing literal line-breaks (CR-LF ["\r\n"], LF ["\n"] or CR ["\r"]):

这是一个函数,它将处理包含文字换行符(CR-LF [ "\r\n"]、LF [ "\n"] 或 CR [ "\r"])的字符串中的完整文本段落:

/**
 * @param \PhpOffice\PhpWord\Element\AbstractContainer $container
 *        E.g. a section or table cell.
 * @param string $text String with literal line breaks as CR-LF, LF or CR.
 * @param string|array|\PhpOffice\PhpWord\Style\Paragraph $paragraphStyle
 * @param string|array|\PhpOffice\PhpWord\Style\Font $fontStyle
 *
 * @return \PhpOffice\PhpWord\Element\TextRun
 */
function addTextWithLineBreaks(
  \PhpOffice\PhpWord\Element\AbstractContainer $container,
  $text,
  $fontStyle,
  $paragraphStyle
) {
  $textRun = $container->addTextRun($paragraphStyle);
  foreach (preg_split('/(\r\n?+|\n)/',
    $text,
    -1,
    PREG_SPLIT_DELIM_CAPTURE
  ) as $i => $part) {
    if ($i & 1) {
      $textRun->addTextBreak(1, $fontStyle, $paragraphStyle);
    } else {
      $textRun->addText($part, $fontStyle, $paragraphStyle);
    }
  }
  return $textRun;
}

PHPWord (0.14.0) currently discards line breaks when reading Word2007 documents – hopefully that will be fixed before 1.0 – but the output from the above is correct when opened in Word.

PHPWord (0.14.0) 当前在读取 Word2007 文档时会丢弃换行符——希望这会在 1.0 之前修复——但在 Word 中打开时,上述输出是正确的。

回答by Maryam Homayouni

You can have a text and add \nwhere ever you want to have line breaks, and do the rest like this:

你可以有一个文本并\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);
}

回答by Jameel Ahmed Ansari

use PHP_EOL for line break it is the only solution for line break in PHPWord

使用 PHP_EOL 换行它是 PHPWord 中换行的唯一解决方案

回答by Andrey Erikin

For correct work, you need to add a text block:

为了正确工作,您需要添加一个文本块:

$string = strtr($string, [
   "\n" => "</w:t>\n<w:br />\n<w:t xml:space=\"preserve\">"
]);