How to combine or embed and insert another .docx file (Microsoft office docx word document) into another one using PHPWord
Joining two .docx document using php (phpword library)
$mainTemplateProcessor = new \PhpOffice\PhpWord\TemplateProcessor("file1");
//$mainTemplateProcessor ->setValue('var_name', $value);
$innerTemplateProcessor = new \PhpOffice\PhpWord\TemplateProcessor("file2");
//$innerTemplateProcessor->setValue('var2_name', $value2);
// extract internal xml from template that will be merged inside main template
$innerXml = $innerTemplateProcessor->gettempDocumentMainPart();
$innerXml = preg_replace('/^[\s\S]*<w:body>(.*)<\/w:body>.*/', '$1', $innerXml);
// remove tag containing header, footer, images
$innerXml = preg_replace('/<w:sectPr>.*<\/w:sectPr>/', '', $innerXml);
// inject internal xml inside main template
$mainXml = $mainTemplateProcessor->gettempDocumentMainPart();
$mainXml = preg_replace('/<\/w:body>/', '<w:p><w:r><w:br w:type="page" /><w:lastRenderedPageBreak/></w:r></w:p>' . $innerXml . '</w:body>', $mainXml);
$mainTemplateProcessor->settempDocumentMainPart($mainXml);
$mainTemplateProcessor->saveAs($result_file_name);
In order for the above code to work, you need to modify edit and add to the TemplateProcessor.php file those two functions:
public function gettempDocumentMainPart()
{
return $this->tempDocumentMainPart;
}
public function settempDocumentMainPart($new)
{
return $this->tempDocumentMainPart = $new;
}
This answer is based on the answer of @pfleu here: https://github.com/PHPOffice/PHPWord/issues/1130
Comments
Post a Comment