How to Merge Word Documents in Java with appendDocument and ImportFormatMode

How to Merge Word Documents in Java with appendDocument and ImportFormatMode

Aspose.Words FOSS for Java merges documents with Document.appendDocument and copies single nodes between documents with NodeImporter. This guide appends a document, imports one paragraph and compares the three ImportFormatMode values, with the library from Maven Central.

Step-by-Step Guide

Step 1: Install the Package

Add the package to your build. The library needs Java 8 or later.

<dependency>
  <groupId>org.aspose</groupId>
  <artifactId>aspose-words-foss</artifactId>
  <version>26.3.0</version>
</dependency>

Step 2: Import the Classes

All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;. The examples are statements: put them in a method that declares throws Exception.


Step 3: Append a Document

target.appendDocument(source, ImportFormatMode.KEEP_SOURCE_FORMATTING) adds the source to the end of the target. The target went from 1 to 2 sections and from 2 to 5 paragraphs, and the appended heading kept the style Heading 1 after saving and reloading.

import com.aspose.words.*;

Document source = new Document();
DocumentBuilder sourceBuilder = new DocumentBuilder(source);
sourceBuilder.getParagraphFormat().setStyleName("Heading 1");
sourceBuilder.writeln("Appendix");
sourceBuilder.getParagraphFormat().setStyleName("Normal");
sourceBuilder.writeln("Text that comes from the source document.");

Document target = new Document();
DocumentBuilder targetBuilder = new DocumentBuilder(target);
targetBuilder.writeln("Main document text.");
System.out.println("Target sections before: " + target.getSections().getCount());
System.out.println("Target paragraphs before: " + target.getChildNodes(NodeType.PARAGRAPH, true).getCount());

target.appendDocument(source, ImportFormatMode.KEEP_SOURCE_FORMATTING);
System.out.println("Target sections after: " + target.getSections().getCount());
System.out.println("Target paragraphs after: " + target.getChildNodes(NodeType.PARAGRAPH, true).getCount());
target.save("merged.docx");

Document reloaded = new Document("merged.docx");
NodeCollection paragraphs = reloaded.getChildNodes(NodeType.PARAGRAPH, true);
for (int i = 0; i < paragraphs.getCount(); i++) {
    Paragraph paragraph = (Paragraph) paragraphs.get(i);
    if (paragraph.getText().trim().length() > 0) {
        System.out.println(paragraph.getParagraphFormat().getStyleName() + ": " + paragraph.getText().trim());
    }
}

The program printed:

Target sections before: 1
Target paragraphs before: 2
Target sections after: 2
Target paragraphs after: 5
Normal: Main document text.
Heading 1: Appendix
Normal: Text that comes from the source document.

Step 4: Import a Single Node

Create a NodeImporter(source, target, mode) and call importNode(node, true). The copy belongs to the target document but has no parent, so add it with appendChild.

import com.aspose.words.*;

Document source = new Document();
DocumentBuilder sourceBuilder = new DocumentBuilder(source);
sourceBuilder.writeln("Paragraph one from the source");
sourceBuilder.writeln("Paragraph two from the source");

Document target = new Document();
DocumentBuilder targetBuilder = new DocumentBuilder(target);
targetBuilder.writeln("Target text");

NodeImporter importer = new NodeImporter(source, target, ImportFormatMode.USE_DESTINATION_STYLES);
Paragraph wanted = source.getFirstSection().getBody().getParagraphs().get(1);
Node imported = importer.importNode(wanted, true);
System.out.println("Imported node belongs to the target document: " + (imported.getDocument() == target));
System.out.println("Imported node has a parent yet: " + (imported.getParentNode() != null));

target.getFirstSection().getBody().appendChild(imported);
System.out.println("Imported node has a parent now: " + (imported.getParentNode() != null));
NodeCollection paragraphs = target.getChildNodes(NodeType.PARAGRAPH, true);
for (int i = 0; i < paragraphs.getCount(); i++) {
    System.out.println(i + ": " + paragraphs.get(i).getText().trim());
}
System.out.println("Source paragraphs are still " + source.getChildNodes(NodeType.PARAGRAPH, true).getCount());

The program printed:

Imported node belongs to the target document: true
Imported node has a parent yet: false
Imported node has a parent now: true
0: Target text
1: 
2: Paragraph two from the source
Source paragraphs are still 3

Step 5: Choose a Mode When Styles Differ

With a 30 pt Heading 1 in the source and a 14 pt Heading 1 in the target, USE_DESTINATION_STYLES gave 14.0 pt, KEEP_SOURCE_FORMATTING gave the style Normal with 30.0 pt applied directly and KEEP_DIFFERENT_STYLES created the style Heading 1_0 at 30.0 pt. The style counts include the Heading 1 that getStyles().get("Heading 1") creates in the new destination document; without that call it had 4 styles.

import com.aspose.words.*;

Document source = new Document();
source.getStyles().get("Heading 1").getFont().setSize(30);
DocumentBuilder sourceBuilder = new DocumentBuilder(source);
sourceBuilder.getParagraphFormat().setStyleName("Heading 1");
sourceBuilder.writeln("Heading from the source");

int[] modes = {ImportFormatMode.USE_DESTINATION_STYLES, ImportFormatMode.KEEP_SOURCE_FORMATTING, ImportFormatMode.KEEP_DIFFERENT_STYLES};
for (int mode : modes) {
    Document target = new Document();
    target.getStyles().get("Heading 1").getFont().setSize(14);
    int before = target.getStyles().getCount();
    target.appendDocument(source, mode);
    Paragraph imported = (Paragraph) target.getChildNodes(NodeType.PARAGRAPH, true).get(1);
    Font font = imported.getRuns().get(0).getFont();
    System.out.println(ImportFormatMode.getName(mode) + ": styles " + before + " -> " + target.getStyles().getCount()
        + ", imported paragraph style " + imported.getParagraphFormat().getStyleName() + ", text size " + font.getSize() + " pt");
}

The program printed:

USE_DESTINATION_STYLES: styles 5 -> 5, imported paragraph style Heading 1, text size 14.0 pt
KEEP_SOURCE_FORMATTING: styles 5 -> 5, imported paragraph style Normal, text size 30.0 pt
KEEP_DIFFERENT_STYLES: styles 5 -> 6, imported paragraph style Heading 1_0, text size 30.0 pt

Common Issues and Fixes

The imported paragraph shows the style Normal. That is what KEEP_SOURCE_FORMATTING produced in a test when the destination already had a different Heading 1: the formatting was applied directly. Use KEEP_DIFFERENT_STYLES to keep the style under a new name.

A style called Heading 1_0 appeared. In the test KEEP_DIFFERENT_STYLES created the style Heading 1_0 for the differing Heading 1.

The imported node is missing from the saved file. importNode returns a node with no parent. Add it with appendChild.

The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.

Frequently Asked Questions

Does appendDocument start a new section?

In the first example it did: the target went from 1 to 2 sections. A source with 2 sections took a target from 1 to 3 sections in a test.

What happens if the destination has no such style?

In a test it was copied: all three modes kept the imported paragraph in the style Heading 1 and copied the style with 30.0 pt. The upstream ImportFormatMode remarks say that with KEEP_SOURCE_FORMATTING it is not always possible to keep the source style.

See Also