来自 PhpWord 的多个 comments.xml 文件

问题描述 投票:0回答:1

我正在使用 PhpWord 创建一个包含注释的文档。我可以成功创建该文件,但当我尝试打开它时,Word 报告它包含不可读的内容。尽管 Word 将继续打开文件,并且注释似乎位于正确的位置,但我仍然希望找到一个优雅的解决方案来阻止 Word 显示警告。

我将.docx文件重命名为.zip,发现该包包含2个comments.xml文件。

Duplicate comments.xml files

这两个文件是相同的,只是一个包含评论的 id,而另一个不包含。

XML file with Comment ID

XML file without Comment ID

下面是代码。如果我不包含评论,效果很好。有什么建议吗?

<?php
ob_start(); // output buffering is turned on
require_once('bootstrap.php');

// Creating the new document...
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->getCompatibility()->setOoxmlVersion(15);

// Adding an empty Section to the document...
$section1 = $phpWord->addSection();

      // A comment
      $comment = new \PhpOffice\PhpWord\Element\Comment('Authors name');
      $comment->addText('Test comment', ['bold' => true]);
      $phpWord->addComment($comment);

      $textrun = $section1->addTextRun();
      $textrun->addText('This ');
      $text = $textrun->addText('is');
      $text->setCommentRangeStart($comment);
      $textrun->addText(' a test');
                        
ob_clean();

$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');

\PhpOffice\PhpWord\Settings::setZipClass(\PhpOffice\PhpWord\Settings::PCLZIP);

// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($temp_file);

header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="duplicates.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');

readfile($temp_file); 
file_get_contents($temp_file);

?>
php phpword
1个回答
0
投票

我可以通过注释掉 PHPWord/src/PhpWord/Writer/Word2007.php 中的第 271 行来解决这个问题。然而,我是面向对象编程的新手,所以这可能不是一个好的解决方案。

private function addComments(ZipArchive $zip, &$rId): void
{
    $phpWord = $this->getPhpWord();
    $collection = $phpWord->getComments();
    $partName = 'comments';

    // Add comment relations and contents
    /** @var \PhpOffice\PhpWord\Collection\AbstractCollection $collection Type hint */
    if ($collection->countItems() > 0) {
        $this->relationships[] = ['target' => "{$partName}.xml", 'type' => $partName, 'rID' => ++$rId];

        // Write content file, e.g. word/comments.xml
        $writerPart = $this->getWriterPart($partName)->setElements($collection->getItems());
// Comment this line:        $zip->addFromString("word/{$partName}.xml", $writerPart->write());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.