如何用phpword创建一个包含其他几个人所有内容的word文档

how to create a word document with all the content of several others with phpword

我必须制作一个包含多个 .docx 文档的所有内容的 .docx 文档

foo.docx
bar.docx
foobar.docx

all-in-one.docx 必须这样构建

  foo.docx content
+ page break
+ bar.docx content
+ page break
+ foobar.docx content

PHP 7.0 | laravel 5.5 | PHP字数 0.15

6 月 30 日被接受的 pull request 建议如下。

循环一个文档的部分并将其插入另一个文档。

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Lorem ipsum');

// Load another document
$phpWord2 = \PhpOffice\PhpWord\IOFactory::load('lorem.docx');

// Add sections to the first document
foreach ($phpWord2->getSections() as $section) {
    $phpWord->addExistingSection($section);
}

所以你基本上只是(未经测试的代码)

<?php
    $documents = ['doc1.docx', 'doc2.docx', 'doc3.docx', 'doc4.docx'];
    $lastDoc = end($documents);

    $mainDoc = new \PhpOffice\PhpWord\PhpWord();

    foreach($documents as $document) {
        $appendDoc = \PhpOffice\PhpWord\IOFactory::load($document);
        foreach ($appendDoc->getSections() as $section) {
            $mainDoc->addExistingSection($section);
        }

        // Add page break after every appended doc except the last one
        if($document != $lastDoc) {
            $section = $mainDoc->addSection();
            $section->addPageBreak();
        }
    }

现在 $mainDoc 应该可以保存了。

另一种可能的解决方案是使用 DocxMerge。不确定它是否支持添加分页符等。