如何使用phpword创建包含其他几个内容的Word文档

时间:2018-10-03 07:31:00

标签: php 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 | PHPWord 0.15

1 个答案:

答案 0 :(得分:1)

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。不确定是否支持添加分页符等。