TextRun中的PHPWord LineBreak不起作用

时间:2016-01-28 15:30:58

标签: php phpword

我找到了一位年长Stack Over Flow Question的建议,但我遇到了问题。我添加了他们描述的方法,但生成的word文件没有换行符(在视觉上和解压缩后检查docx文件)。没有错误,所以这个方法似乎做的不是我想要的。我这样做是因为我需要\n个字符而且我确实使用PHPRtfText使其工作正常,但是兼容性问题并且它似乎更好地用作Word2007文件,所以我相应地转换了代码。虽然,也许我把它放在错误的位置,但这里是修改后的功能:

/lib/PHPWord/Writer/Word2007/Base.php:

protected function _writeTextRun(PHPWord_Shared_XMLWriter $objWriter = null,    PHPWord_Section_TextRun $textrun)
{
  $elements = $textrun->getElements();
  $styleParagraph = $textrun->getParagraphStyle();

  $SpIsObject = ($styleParagraph instanceof PHPWord_Style_Paragraph) ? true : false;

  $objWriter->startElement('w:p');

  if($SpIsObject)
  {
     $this->_writeParagraphStyle($objWriter, $styleParagraph);
  }
  elseif(!$SpIsObject && !is_null($styleParagraph))
  {
     $objWriter->startElement('w:pPr');
        $objWriter->startElement('w:pStyle');
           $objWriter->writeAttribute('w:val', $styleParagraph);
        $objWriter->endElement();
     $objWriter->endElement();
  }

  if(count($elements) > 0)
  {
     foreach($elements as $element)
     {
        if($element instanceof PHPWord_Section_Text)
        {
           $this->_writeText($objWriter, $element, true);
        }
        elseif($element instanceof PHPWord_Section_Link)
        {
           $this->_writeLink($objWriter, $element, true);
        }
     }
  }
  elseif($element instanceof PHPWord_Section_TextBreak)
  {
     $objWriter->writeElement('w:br');
  }

  $objWriter->endElement();
}

我通过以下方式调用它:

test1.php:

$PHPWord = new PHPWord();;
$PHPWord->setDefaultFontName('Calibri');
$PHPWord->setDefaultFontSize(11);

$section = $PHPWord->createSection();
$textrun = $section->createTextRun();
$textrun->addText( "---------------");
$textrun->addTextBreak();
$textrun->addText( "$name", array('bold'=>true ) );

最后在 /lib/PHPWord/Section/TextRun.php:

public function addTextBreak($count = 1)
{
    for($i=1; $i<=$count; $i++)
    {
        $this->_elementCollection[] = new PHPWord_Section_TextBreak();
    }
}

还有什么我可以添加来帮助吗?我真的需要这个工作,不能再把班级换成其他东西了。

我正在严格格式化文本,因此是textrun,但是我需要在每一行之后\n而不是一个部分,因为它需要是同一段,因此\n\n不会是这项努力是可以接受的。

1 个答案:

答案 0 :(得分:0)

我当然认为我尝试了这个但是也许我没有把它保存在网络服务器上,但将elseif移到更高的elseif块上就可以了。

if(count($elements) > 0) 
  {
     foreach($elements as $element) 
     {
        if($element instanceof PHPWord_Section_Text) 
        {
           $this->_writeText($objWriter, $element, true);
            } 
        elseif($element instanceof PHPWord_Section_Link) 
        {
           $this->_writeLink($objWriter, $element, true);
            }
        elseif($element instanceof PHPWord_Section_TextBreak)
        {        
           $objWriter->writeElement('w:br');
        }              
     }
  } 
  $objWriter->endElement();
}
相关问题