【发布时间】:2016-05-06 01:40:40
【问题描述】:
我从一位年长的 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 是不可接受的.
【问题讨论】: