Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merging multiple docx files created using templates? #2420

Open
ozilion opened this issue Jul 10, 2023 · 1 comment
Open

Merging multiple docx files created using templates? #2420

ozilion opened this issue Jul 10, 2023 · 1 comment

Comments

@ozilion
Copy link
Contributor

ozilion commented Jul 10, 2023

Hi all,

I would like to know, if possible, how to merge multiple docx files created by TemplateProcessor? I have at least 10 different templates and can create different number of docx files depends on some criterias, it could be 1 or 3 or 5 for example, at the end i have to combine those created docx files into 1 combined docx file. Is it possible with PHPWord?

Thanks in advance.

@pageantry
Copy link

If you only need to merge content (while maintaining formating/styling), you can use the following approach:

<?php

namespace Template;

use PhpOffice\PhpWord\TemplateProcessor;

class Template extends TemplateProcessor
{
    private const OPEN_BODY_TAG = '<w:body>';
    private const CLOSE_BODY_TAG = '</w:body>';

    public function getBodyContent(): string
    {
        $bodyStart = mb_strpos($this->tempDocumentMainPart, self::OPEN_BODY_TAG) + mb_strlen(self::OPEN_BODY_TAG);
        $bodyEnd = mb_strpos($this->tempDocumentMainPart, self::CLOSE_BODY_TAG, $bodyStart);

        $bodyContent = mb_substr($this->tempDocumentMainPart, $bodyStart, $bodyEnd - $bodyStart);

        return $bodyContent;
    }

    public function mergeXmlBody(string $xmlBody): void
    {
        $this->tempDocumentMainPart = str_replace(
            self::CLOSE_BODY_TAG,
            $xmlBody . self::CLOSE_BODY_TAG,
            $this->tempDocumentMainPart
        );
    }
}

How to use:

<?php

function merge(array $files): string
{
    $mergedFile = str_replace(basename($files[0]), time() . '_merged.docx', $files[0]);
    $main = new \Template\Template($files[0]);
    unset($files[0]);

    $body = [];

    foreach ($files as $file) {
        $template = new \Template\Template($file);
        $body[] = $template->getBodyContent();
    }

    $body = implode('', $body);

    $main->mergeXmlBody($body);
    $main->saveAs($mergedFile);

    return $mergedFile;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants