Importing and Merging Documents
Overview
This guide shows how to append one Word document to another in Java, import single nodes with NodeImporter and choose an ImportFormatMode with Aspose.Words FOSS for Java. Document.appendDocument(source, importFormatMode) appends the content of another document to the end of this one. To use a node from another document you import it with a NodeImporter (or DocumentBase.importNode), which copies it into the destination document and applies an ImportFormatMode to the styles. The ImportFormatMode values are USE_DESTINATION_STYLES, KEEP_SOURCE_FORMATTING and KEEP_DIFFERENT_STYLES. The examples below were compiled and run on Java 8, 17 and 21 with identical output.
Prerequisites
| Requirement | Detail |
|---|---|
| Java | 8 or later |
| Dependency | The package from Installation |
| Import | import com.aspose.words.*; |
| Code | The examples are statements. Put them in a method that declares throws Exception. |
Append a Document
Build a source document with a Heading 1 paragraph and a text paragraph, then call target.appendDocument(source, ImportFormatMode.KEEP_SOURCE_FORMATTING). The target went from 2 to 5 paragraphs and from 1 to 2 sections (both counts are printed by the program): the appended content started a new section. The reloaded file listed the target text with the style Normal, the appended heading as Heading 1 and the appended text as Normal.
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.Import a Single Node
A NodeImporter takes the source document, the target document and an ImportFormatMode, and importNode(node, true) returns a copy that belongs to the target document. The imported paragraph had no parent until appendChild added it to the body of the target: getDocument() was the target and getParentNode() was null before, and not null after. The source document still had its 3 paragraphs.
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 3Compare the Import Format Modes
The example gives the source a 30 pt Heading 1 and the destination a 14 pt Heading 1, so the two documents disagree, and appends the source in each mode. USE_DESTINATION_STYLES gave the imported paragraph the destination style Heading 1 at 14.0 pt, with the style count unchanged at 5. KEEP_SOURCE_FORMATTING gave it the style Normal with the source text size 30.0 pt applied directly, and the style count was unchanged. KEEP_DIFFERENT_STYLES added a style named Heading 1_0 (6 styles) and the paragraph used it at 30.0 pt. The style counts include the Heading 1 style that getStyles().get("Heading 1") creates in the new destination document: without that call the destination 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 ptTips and Best Practices
- Pick the mode on purpose when the two documents define the same style differently. In the test of the last example the three modes gave three different results for the same source paragraph, as listed above.
- When the destination does not have the style at all, the style is copied: in a test with a 30 pt Heading 1 in the source and no Heading 1 in the destination, with a fresh source document all three modes left the imported paragraph in the style Heading 1, the style was copied with 30.0 pt and the style count went from 4 to 5. The upstream remarks of
ImportFormatMode(in the source) note that withKEEP_SOURCE_FORMATTINGit is not always possible to keep the source style even if it does not exist in the destination, so check your own documents. A freshDocumenthas 4 styles;getStyles().get("Heading 1")creates that built-in style, which is why the conflict test already reports 5 before the import. - An imported node has no parent until you insert it, so call
appendChildorinsertBeforeafterimportNode. - In a test with
KEEP_SOURCE_FORMATTING, a source with 2 sections took the target from 1 to 3 sections and the source still had 2, so each source section was appended as its own section.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| The compiler reports cannot find symbol for Document. | The com.aspose.words package is not imported. | Add import com.aspose.words.*;. |
| 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. |
| The imported paragraph has the style Normal. | With KEEP_SOURCE_FORMATTING and a style of the same name that differs in the destination, the formatting is applied directly and the style is not kept. | Use KEEP_DIFFERENT_STYLES if you want the source style kept under a new name, or USE_DESTINATION_STYLES for the destination look. |
| A style named Heading 1_0 appeared. | KEEP_DIFFERENT_STYLES copied the source style under a new name because the destination has a different Heading 1. | Use USE_DESTINATION_STYLES if you do not want extra styles. |
| An imported node is not in the saved document. | importNode only copies the node into the target document; it has no parent. | Add it with appendChild or insertBefore. |
FAQ
How do I merge two documents?
Call target.appendDocument(source, ImportFormatMode.KEEP_SOURCE_FORMATTING) or another mode, as the first example does, and save the target.
Does appendDocument change the source document?
In a test the source still had its 2 sections after appendDocument. With NodeImporter, the second example, the source kept its 3 paragraphs.
What are the ImportFormatMode values?
USE_DESTINATION_STYLES, KEEP_SOURCE_FORMATTING and KEEP_DIFFERENT_STYLES. The one-line descriptions on the ImportFormatMode reference page are terse; for a same-name conflict the behaviour in the last example is what the test observed.
Which formats were tested?
Only DOCX: the first example saves a DOCX file and reloads it; the others work on documents in memory.
API Reference Summary
| Class / Method | Description |
|---|---|
NodeImporter | Allows to efficiently perform repeated import of nodes from one document to another. |
ImportFormatMode | Specifies how formatting is merged when importing content from another document. |
Document.appendDocument(srcDoc, importFormatMode) | Appends the specified document to the end of this document. |
DocumentBase.importNode(srcNode, isImportChildren) | Imports a node from another document to the current document. |
NodeImporter.importNode(srcNode, isImportChildren) | Imports a node from one document into another. |
CompositeNode.appendChild(newChild) | Adds the specified node to the end of the list of child nodes for this node. |