Practical phpdocx

Merging

Introduction

One of the most remarkable features of phpdocx is the possibility of merging two or more documents. You can merge them to obtain a single document, in the same way as with PDF files.

Besides these merging options, you can also add DOCX, HTML, MHT and RTF files in new documents and replace them for placeholders in templates.

Merging DOCX documents

In order to merge documents, choose the class MultiMerge, available for Advanced and Premium licenses.

Its use is very simple. First, include this class:

Then, instance it:

Finally, call the mergeDocx method, with the following signature:

The available parameters are:

  • $firstDocument: name of the first document to merge.
  • $documentArray: array of documents you want to add, by order of insertion.
  • $finalDocument: name of the resulting DOCX document.
  • $options: array of additional options. These are the ones available:
    • mergeType: 0 or 1, to preserve or discard the sections of each document you want to add.
    • numbering, continue or restart: it keeps the page numbering or resets it.
    • lineBreaks: to insert as much page breaks as indicated with an integer.
    • preserveStyleDefaults, true or false: forces the styles of the first document to be the main style over the remaining documents.

For example, for merging the documents first.docx, second.docx and third.docx, write this line of code:

Merging PDF documents

Merging PDF files is as simple as with docx files. First, instance the class:

Then, call this method:

These are the available options:

The available parameters are:

  • $documentArray: array of documents by order of insertion.
  • $finalDocument: name of the final PDF file.

For example, write this for merging three PDF files:

Adding other documents

If you need to add documents that already exist or replace placeholders by files, phpdocx provides two methods.

For adding documents to other new ones, call this method:

To replace a placeholder in a template for a document, use this method:

Thanks to these methods you can easily add DOCX, HTML, MHT, and RTF files.

The most important of the available options is matchSource. It is a boolean var that forces Word to respect as much as possible the original styles and structures of the inserted document.

In the same options parameter, indicate with the ‘scr‘ key the document to insert:

Here's a simple example for adding a DOCX in a new document:

On the other hand, for replace a placeholder in a template, run this code:

Tips and tricks

The altChunk tag, used by addExternalFile and replaceVariableByExternalFile methods, is only compatible with MS Word 2007 and later versions on Windows. Other office suites like LibreOffice, OpenOffice or MS Word for Mac are not compatible with altChunk.

The MultiMerge class doesn't use altChunk tags to merge documents.