DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Merge Word Documents in Java applications

In this article, we will introduce how to merge multiple Word documents into one Word document by using Free Spire.Doc for Java.

Combine two Word documents into one Word document

Free Spire.Doc for java offers an insertTextFromFile() method to merge Word documents by inserting content from a source document into a destination document. In the resulted Word document, the inserted content starts from a new page and it follows the source document’s header, footer and background style.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class MergeWord {
    public static void main(String[] args)  {

        //File path of the first document
        String filePath1 = "Sample1.docx";
        //File path of the second document
        String filePath2 = "Sample2.docx";

        //Load the first document
        Document document = new Document(filePath1);

        //Insert content of the second document into the first document
        document.insertTextFromFile(filePath2, FileFormat.Docx_2013);

        //Save the document
        document.saveToFile("MergeWord.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

merge word

Merge Word document on the same page

If we want to combine the two Word documents together and the inserted content follows the last paragraph of the original Word document, Free Spire.Doc for Java also supports to do like this. Please check the code snippets as below:

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class mergeDocsOnSamePage {
    public static void main(String[] args)  {

        //File path of the first document
        String filePath1 = "Sample1.docx";
        //File path of the second document
        String filePath2 = "Sample2.docx";

        //Load the first document
        Document document1 = new Document(filePath1);
        //Load the second document
        Document document2 = new Document(filePath2);

        //Get the last section of the first document
        Section lastSection = document1.getLastSection();

        //Traverse sections
        for (Object sectionObj : document2.getSections()) {
            Section section=(Section)sectionObj;
            // Traverse body ChildObjects
            for (Object docObj : section.getBody().getChildObjects()) {
                DocumentObject obj=(DocumentObject)docObj;
                // Clone to destination document at the same page
                document1.getSections().get(0).getBody().getChildObjects().add(obj.deepClone());
            }
        }
        //Save the document
        document1.saveToFile("MergeWord2.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Merge Word documents

Top comments (0)