Okay, recently i have to edit a word document using Laravel. That’s in theory a simple thing if you’re gonna use PHPOffice but the problem shows up when you have a template. And First page is different than the second page and one and one. So, to do that there was a few things I’ve stepped during the journey. One was the most important. When merging entire document into one it can only have one footer and header. The second document footer and header are ignored and will cause troubles if not deleted properly. And another thing was a page break.

Okay so what to do with what I’ve used. First let’s do the same thing as I did which is creating 2 templates in word. One for the main page with footer and header. And the second template with the content of your desire. In word if you want to replace something just type ${name_to_replace} and the framework will replace that with the data you entered. Save those doc files as .docx

 There is a special trick that work for MS Word for page break. That’s a small code that you are inserting instead of some value. The code will look like this. ( Word value to replace ${break}  )

$doc->setValue(‘break’, ‘<w:p><w:r><w:br w:type=”page”/></w:r></w:p>’);

 Please see here is a code snippet that uses a Template Processor of PHPOffice.
The effortless way of editing a template. I just load the template and save it.
Make sure you will enter a full template path.

$doc = new TemplateProcessor($storage_path $template_name);
$doc->setValue(‘word_variable’, ‘Johnnn Smith’ );

Okay now when you have one document generated.
Let’s generate another one using the second template. And save it.
So now we have doc1.docx and doc2.docx.

And now there is a trick. To combine multiple documents into one. I’ve used DocxMerge.

Entire code for that is this

$pages = [ path_to_file_1, path_to_file_2 ];
$dm = new DocxMerge();
$dm->merge($pages, $this->temp_path . $this->full_final_file_path_name);


And that’s really it. For some reason, the docx Merge is producing temp files so if you want to get rid of them, I’ve used glob for that.

$temp_files = glob($temp_path . ‘*.tmp’);

         foreach ($temp_files as $file) {