docx icon indicating copy to clipboard operation
docx copied to clipboard

Merging previously merged docs results in corrupted document

Open rc1972 opened this issue 6 years ago • 2 comments

Hi, thank you for this library.

I noticed that if you try to merge documents resulting from previous merging operation you get a corrupted file. In my scenario there are three files:

  • fileHeader.docx
  • file1.docx
  • file2.docx

I apply DocxMerge to fileHeader.docx + file1.docx and generate file1Merged.docx; then I apply DocxMerge to fileHeader.docx + file2.docx obtaining file2Merged.docx. Finally, I apply DocxMerge to file1Merged.docx + file2Merged.docx and obtain a corrupted file. I looked into the last generated docx and found out that the problems is related to the presence of two inner docx with the same name (Part1.docx). I used this workaround: in save function of DocxMerge class I added a $cnt parameter to change the name of "Part" files as follows:

public function save($outDocxFilePath, $addPageBreak = false, $cnt=0) ... for ($i = 1; $i < count($this->files); $i++) { $docx->addFile($this->files[$i], "part" . ($cnt*1000 + $i) . ".docx", "rId10" . ($cnt*1000 + $i), $addPageBreak); }

Of course, when I call this function I pass a counter as last parameter, i.e.: $docxMerge = \Jupitern\Docx\DocxMerge::instance() ->addFiles(array('fileHeader.docx', 'file1.docx')) ->save('file1Merged.docx', false, 1); // First file: $cnt=1 $docxMerge = \Jupitern\Docx\DocxMerge::instance() ->addFiles(array('fileHeader.docx', 'file2.docx')) ->save('file2Merged.docx', false, 2); // Second file: $cnt=2 $docxMerge = \Jupitern\Docx\DocxMerge::instance() ->addFiles(array('file1Merged.docx', 'file2Merged.docx')) ->save('Result.docx', true); // Resulting file (not corrupted)

By the way, I need to apply DocxMerge in more steps because when I merge fileFeader1.docx + file1.docx I don't want page break, while the last merging needs page breaks (I think that the same issue would occur using krustnic class, but in that case it can be avoided using one-step merging).

Hope this helps. Regards.

rc1972 avatar May 22 '19 08:05 rc1972

If you dont want to the page break, leave the third parameter to blank

$docxMerge = \Jupitern\Docx\DocxMerge::instance()
->addFiles(array('fileHeader.docx', 'file1.docx'))
->save('file1Merged.docx', false); 

cyberformed avatar Jun 22 '19 09:06 cyberformed

This code returns me file_1.docx in result.docx but not merge the file_2.docs with file_1.docx

`$dir = public_path(). '\\uploads\\';
       // Docx template
       $docx = Docx::instance()
                ->setTemplate($dir.'final.docx')
                ->save($dir.'result.docx');
        
    $docxMerge =  \Jupitern\Docx\DocxMerge::instance()
            ->addFiles([ $dir.'file_1.docx',  $dir.'file_2.docx'])
            ->save($dir.'result.docx', true);`

faraz08 avatar Oct 22 '19 10:10 faraz08